kazinix
kazinix

Reputation: 30093

Dependency Injection on SignalR in ASP.NET Core

Note:

For brevity, I reduced my codes and made it simple.

Codes/Setup:

I have a class:

class MyService
{
    public Guid InstanceID = Guid.NewGuid;

I added MyService in my services as scoped:

public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<MyService, MyService>();

Then in my view, I inject the service:

@inject MyService _myService

@_myService.InstanceID //display

The code above displays different result each request, as expected from a scoped service.

However, when injecting the service in SignalR Hub, I always get the same output.

MyHub(MyService myService)
{
    _myService = myService; 
}

public void Test()
{
     Clients.Caller.Log(_myService.InstanceID); //Log is a custom function in JS

Although the Hub itself is instantiated every call to Test(), the instance of MyService being injected to it is always the same.

My Requirement:

I want a new instance of MyService to be injected in Hub the same way in Controller/View every request.

Question:

Is this the default behavior of SignalR? Or am I doing something wrong?

Packages Used:

<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />

<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="0.2.0-*" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Server" Version="0.2.0-rtm-22752" />

Upvotes: 4

Views: 2798

Answers (1)

RredCat
RredCat

Reputation: 5421

You have to change AddScoped to Transient. Because the first one is created once per request and second is created each time it is requested.

You could check more details in Service Lifetimes and Registration Options section.

Also, you could check How to handle connection lifetime events in the Hub class for the understanding difference with Controller/View request.

Upvotes: 2

Related Questions