从另一个对象中获取SignalR Core中的Hub Context

时间:2018-01-23 02:49:14

标签: c# asp.net-core asp.net-core-signalr

我正在使用Microsoft.AspNetCore.SignalR(最新版本),并希望从另一个不是Controller的对象中获取集线器上下文。在“完整”SignalR中,我可以使用GlobalHost.ConnectionManager.GetHubContext<MyCoolHub>();

我见过很多例子,只是将Microsoft.AspNetCore.SignalR.IHubContext<MyCoolHub>作为参数添加到Controller的Ctor中,但没有示例(可行的)。

ETA:

所以,这就是我的工作。这是hacky吗?

public class MyHub : Hub
    public static IHubContext<MyHub> GlobalContext { get; private set; }
    public MyHub(IHubContext<MyHub> ctx){
        GlobalContext = ctx;
    }
}

然后我可以这样称呼它:

await MyHub.GlobalContext.Clients.All.InvokeAsync(...)

2 个答案:

答案 0 :(得分:8)

只需在调用方构造函数上设置IHubContext<MyHub> hubContext

我建议使用.net核心默认DI容器机制,而不是创建静态属性。

请参阅How do I get a reference to a Hub?

public class MyHub : Hub
{
}

public class CallingSideClass
{
    private readonly IHubContext<MyHub> _hubContext;

    public CallingSideClass(IHubContext<MyHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task FooMethod(...)
    {
        await _hubContext.Clients.All.InvokeAsync(...);
    }
}

public class Startup
{...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddScoped<CallingSideClass>();
    }
    ... 
}

答案 1 :(得分:1)

所以在从接受的答案中查看this example之后,我并没有完全了解他要去的地方,所以我尝试了一些事情,我想我得到了他说的话。因此,对于将来遇到此问题的人,我想将该示例更改为完整的示例。

因此,我们将创建一个“共享方法”,如示例中所示:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace YouDontNeedToKnow.Core.Main.Hubs
{
    internal class HubMethods<THub> where THub : Hub
    {
        private readonly IHubContext<THub> _hubContext;

        public HubMethods(IHubContext<THub> hubContext)
        {
            _hubContext = hubContext;
        }

        public Task InvokeOnGroupAsync(string groupName, string method, params object[] args) =>
            _hubContext.Clients.Group(groupName).InvokeAsync(method, args);

        public Task InvokeOnAllAsync(string method, params object[] args) =>
            _hubContext.Clients.All.InvokeAsync(method, args);

        public Task AddConnectionIdToGroupAsync(string connectionId, string groupName) =>
            _hubContext.Groups.AddAsync(connectionId, groupName);

        // ...
    }
}

然后,在你的Hub对象中,添加一个构造函数,如下所示:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace YouDontNeedToKnow.Core.Main.Hubs
{
    internal class MyHub : Hub
    {
        public static string HubName => "myHub";

        private readonly HubMethods<MyHub> _hubMethods;

        public PlayerServicesHub(HubMethods<MyHub> hubMethods)
        {
            _hubMethods = hubMethods;
        }

        public override Task OnConnectedAsync()
        {
            return base.OnConnectedAsync();
        }
    }
}

Startup.cs中,您可以像这样注入共享类:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<HubMethods<MyHub>>();
    services.AddSignalR();
    services.AddMvc();
}

这仍然可以正常工作:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider sp)
{
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseSignalR(routes =>
    {
        routes.MapHub<MyHub>(MyHub.HubName);
    });
    app.UseMvc();
    // This is just an example line of how you can get the hub with context:
    var myHub = sp.GetService<HubMethods<MyHub>>();
}