3
votes

I am using SignalR on different places of my web project. In my Controllers and HostedService this seems to be working fine. Clients instantiate connections with my hub and I can communicate with them back using an IHubContext instance, injected in the constructor of every controller/hostedservice.

I am having another singleton, running in Background (No HosteService or BackgroundTask). This class is getting IHubContext injected in the constructor also. Still every time it gets called, it seems like this singleton is having a different instance of IHubContext, since this context has no clients/groups connected to it.

This class is being registered as this in the startup function:

services.AddSingleton<IServiceEventHandler<TourMonitorEvent>, TourMonitorEventHandler>();

To configure SignalR I am doing the following in ConfigureServices:

services.AddSignalR().AddNewtonsoftJsonProtocol();

and the following in configure:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<MyHubClass>("/hubEndpoint");
    endpoints.MapControllers();
});

the IHubContext ist bein injected as following in both Controllers/Hostedservices and the singleton:

public class MySingleton : IHandler<SomeGenericClass>
{
    private readonly IHubContext<MyHubClass> _hubContext;

    public MySingleton(IHubContext<MyHubClass> hubContext)
    {
        _hubContext = hubContext;
    } 
}

Are Controllers/HosteService being instantiated differently than my Singleton, in a way that might affect IHubContext instantiation?

1
Please provide the code how you are injecting the IHubContext ;)Kiril1512
@Kiril1512 I have edited to answer, adding the injection of IHubContextmh133

1 Answers

0
votes

As said in the documentation:

Hubs are transient.

So since you Singleton is not a HostedService or a BackgroundTask, I would recomend to inject the hub using a DI.

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

Try this and verify if the context now is as you expected.