Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Hub Context in SignalR Core from within another object

I am using Microsoft.AspNetCore.SignalR (latest release) and would like to get the hub context from within another object that's not a Controller. In the "full" SignalR, I could use GlobalHost.ConnectionManager.GetHubContext<MyCoolHub>();

I have seen a lot of examples of just adding Microsoft.AspNetCore.SignalR.IHubContext<MyCoolHub> as a parameter to the Ctor of a Controller, but no examples (that work) for otherwise.

ETA:

So, this is what I have working. Is this hacky?

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

Then I can call it as so:

await MyHub.GlobalContext.Clients.All.InvokeAsync(...)
like image 991
Andy Avatar asked Jan 23 '18 02:01

Andy


People also ask

Is SignalR deprecated?

SignalR is deprecated. May I know the latest package for the same. The package Microsoft. AspNetCore.

What is IHubContext?

The IHubContext is for sending notifications to clients, it is not used to call methods on the Hub . View or download sample code (how to download)

What is hubName in SignalR?

SignalR Hubs are a way to logically group connections as documented. Take an example of a chat application. A group of users could be part of the same hub which allows for sending messages between users in the group. The hubName here can be any string which is used to scope messages being sent between clients.

Is SignalR hub transient?

SignalR handles the serialization and deserialization of complex objects and arrays in your parameters and return values. Hubs are transient: Don't store state in a property on the hub class.


1 Answers

Just set IHubContext<MyHub> hubContext on calling-side constructor.

I would recommend using .net core default DI container mechanism, not creating static property.

Please refer to 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>();
    }
    ... 
}
like image 106
idubnori Avatar answered Sep 19 '22 17:09

idubnori