0

I'm using Microsoft.AspNetCore.SignalR (1.1.0)

I have some services in startup.cs:

services.AddSingleton<IHostedService, MySingletonService>();
services.AddScoped<MyScopedService >();

Now I want to use this service in my hub, so I inject it:

private readonly MyScopedService _cs;
private readonly MySingletonService _ss;
public MyHub(MyScopedService cs, MySingletonService ss)
{
    _cs = cs;
    _ss= ss;
}

This works only for the scoped service, as soon as the service is singleton the hub never gets called and cannot connect in the browser. Why is this not possible? I just want the existing instance of the singleton service, call a method and then let it go again.

JerMah
  • 693
  • 5
  • 17
  • There's something else going on here. There's no problem using a singleton service inside something with a more limited lifetime like the hub. You need to provide a bit more information here. Perhaps post the code for the service that is causing issues and/or your actual hub code instead of sample code. Look at the console output and see if you're getting any exceptions. – Chris Pratt Mar 06 '19 at 15:13

1 Answers1

0

This has nothing to do with SignalR. Since I created my service as an IHostedService I would also need to inject it as an IHostedService which is impossible because I have multiple IHostedServices and only want this specific one. The solution is to inject as a normal singleton and then start it.

services.AddSingleton<MySingletonService>();

//Start the background services
services.AddHostedService<BackgroundServiceStarter<MySingletonService>>();

I found the solution here: https://stackoverflow.com/a/51314147/1560347

JerMah
  • 693
  • 5
  • 17