1
votes

Can I inject a signalR hub (ChatHub derives from Hub) into a service by doing the following:

in Startup.cs:

services.AddSingleton<ChatHub>();

To inject in another service:

    public AnotherClass(ChatHub chatHub)(....

... chatHub.CallMethod(...

Its working but it is a good idea? I always find the IHubContext for that purpose, but why should I use them?

1
No, you can't. Use the IHubContext. docs.microsoft.com/aspnet/core/signalr/…Brennan
Thanks for the comment. Do you know why? Because I can register the hub as singleton to inject it and it us workingmoinster

1 Answers

0
votes

SignalR expects the Hub to be created separately for each message. You need to add it as a Transient service if you want your Hub to be in DI. You generally shouldn't resolve the Hub out of DI. If you need to share code between your Hub and some other component, I'd suggest using either IHubContext or putting the shared code in a separate DI service instead.

private IHubContext<ChatHub, IChatHub> ChatHub
{
    get
    {
        return this.serviceProvider.GetRequiredService<IHubContext<ChatHub, IChatHub>>();
    }
}