.Net Core 2.0 中的 SignalR 依赖注入
SignalR Dependency Injection in .Net Core 2.0
我是 SignalR 的新手,正在尝试在 Asp.Net Core 2.0 中使用 SignalR v1.0.0-alpha2-final 创建聊天应用程序,并且需要在 ChatHub 中使用依赖注入。我发现的所有示例似乎都已过时或与 Asp.Net Core 无关。
有谁知道如何正确地做到这一点?
编辑:澄清一下,我知道如何做 DI en Asp.Net Core,问题是我不知道如何在 SignalR Hub 中做。
在 .NET Core 2 中,依赖注入作为一项功能出现 - 您不需要添加像 Unity 等包。This 是官方文档。
基本上,当拥有 .NET Core 应用程序时,您有入口点 Program.cs
和 Startup.cs
文件,它们在应用程序初始启动时执行。
具有依赖注入的 'magic' 发生在 Startup.cs
中。在那里(默认情况下)你有
public void ConfigureServices(IServiceCollection services)
{
/// code
}
要添加注射,您需要执行以下操作:
services.AddTransient<IMyInterface, MyClassImplementingMyInterface>();
除了 AddTransient
还有 2 种可能性,它们定义了服务的生命周期。它们是:AddSingleton
和 AddScoped
。 我上面提到的答案和文档很好地解释了所有这些的含义,但用几句话来说:
Depending on how we configure the lifetime for this service, the
container will provide either the same or different instances of the
service to the requesting class.
AddTransient
- 对象总是不同的;一个新实例是
提供给每个控制器和每个服务。
AddScoped
- 请求中的对象相同,但是
不同的请求不同
AddSingleton
- 每个对象的对象都相同
以及每个请求(无论实例是否在
配置服务)
对于 SignalR,有一个 SignalRAppBuilderExtensions
class 可以为您提供 UseSignalR
方法。
在Startup.cs
中:
using Microsoft.AspNetCore.Builder;
public void Configure(IApplicationBuilder app)
{
app.UseSignalR(routes =>
{
routes.MapHub<YourHub>("/yourhub");
}
}
然后照常营业
public class YourHub: Hub
{
public YourHub(Stuff stuff)
{
}
}
版本:Microsoft.AspNetCore.SignalR1.0.0-preview1-final
我是 SignalR 的新手,正在尝试在 Asp.Net Core 2.0 中使用 SignalR v1.0.0-alpha2-final 创建聊天应用程序,并且需要在 ChatHub 中使用依赖注入。我发现的所有示例似乎都已过时或与 Asp.Net Core 无关。
有谁知道如何正确地做到这一点?
编辑:澄清一下,我知道如何做 DI en Asp.Net Core,问题是我不知道如何在 SignalR Hub 中做。
在 .NET Core 2 中,依赖注入作为一项功能出现 - 您不需要添加像 Unity 等包。This 是官方文档。
基本上,当拥有 .NET Core 应用程序时,您有入口点 Program.cs
和 Startup.cs
文件,它们在应用程序初始启动时执行。
具有依赖注入的 'magic' 发生在 Startup.cs
中。在那里(默认情况下)你有
public void ConfigureServices(IServiceCollection services)
{
/// code
}
要添加注射,您需要执行以下操作:
services.AddTransient<IMyInterface, MyClassImplementingMyInterface>();
除了 AddTransient
还有 2 种可能性,它们定义了服务的生命周期。它们是:AddSingleton
和 AddScoped
。
Depending on how we configure the lifetime for this service, the container will provide either the same or different instances of the service to the requesting class.
AddTransient
- 对象总是不同的;一个新实例是 提供给每个控制器和每个服务。AddScoped
- 请求中的对象相同,但是 不同的请求不同AddSingleton
- 每个对象的对象都相同 以及每个请求(无论实例是否在 配置服务)
对于 SignalR,有一个 SignalRAppBuilderExtensions
class 可以为您提供 UseSignalR
方法。
在Startup.cs
中:
using Microsoft.AspNetCore.Builder;
public void Configure(IApplicationBuilder app)
{
app.UseSignalR(routes =>
{
routes.MapHub<YourHub>("/yourhub");
}
}
然后照常营业
public class YourHub: Hub
{
public YourHub(Stuff stuff)
{
}
}
版本:Microsoft.AspNetCore.SignalR1.0.0-preview1-final