简体   繁体   English

ASP.NET核心中SignalR的依赖注入

[英]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: 我在我的服务中添加了MyService作为作用域:

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. 但是,在SignalR Hub中注入服务时,我总是得到相同的输出。

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. 尽管每次调用Test()都会实例化Hub本身,但是注入它的MyService实例总是相同的。

My Requirement: 我的要求:

I want a new instance of MyService to be injected in Hub the same way in Controller/View every request. 我想在Controller / View中以相同的方式在Hub中注入一个新的MyService实例。

Question: 题:

Is this the default behavior of SignalR? 这是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" />

You have to change AddScoped to Transient . 您必须将AddScoped更改为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. 此外,您可以检查如何处理Hub类中的连接生存期事件,以了解与Controller / View请求的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM