Create hub instance SignalR 3

2019-09-13 16:00发布

问题:

I am tring to create an instance of a Hub so that a can call a method on all of the clients. In Signalr 2 I would have used.

GlobalHost.ConnectionManager.GetHubContext<Hub>();

But this seems to be missing in Signalr 3 I tried the following but I get an error.

IHubActivator.Create
Using a Hub instance not created by the HubPipeline is unsupported.

Does anybody know how this can be accomplished in SignalR 3?

I am using signalr3 rc1

回答1:

You can resolve the instance using dependency injection;

public void MyController : Controller 
{
    public MyController(IHubContext<MyHub, IMyClient> context)
    {
        context.Clients.All.MyMethod("Hi there!"); // strongly typed 
    }

    // or

    public MyController(IHubContext<MyHub> context)
    {
        context.Clients.All.MyMethod("Hi there!"); // dynamic
    }
}

Or manually;

public void Configure(IApplicationBuilder app) 
{
    var context = app.ApplicationServices.GetRequiredService<IHubContext<MyHub>>();
    context.Clients.All.MyMethod("Hi there!");
}