从任何地方检索 SignalR 3.0 中的集线器上下文的最佳方式
Optimal way to retrieve hub context in SignalR 3.0 from anywhere
我正在使用 SignalR 3.0 开发 Asp .NET 3.1 应用程序,我需要能够随时访问 hubcontext。我定期接收数据并处理它,以便在计时器事件触发时将其推送给客户端。这意味着当客户端调用集线器方法或通过控制器或中间件时,我可以依赖访问集线器上下文的能力。由于我无法在此版本的 signalR 中使用 GlobalHost,因此最佳方法是什么?
我尝试了几种不同的方法,我最初想保留对 hubcontext 的静态引用,但我认为这不是一个非常可靠的方法。我想保留对 IServiceProvider
的静态引用,但是当我的计时器触发时,服务提供者已经被处理掉了。有什么建议吗?
如果您使用标准 Asp.Net 核心依赖注入 (IServiceCollection),您可以在服务的构造函数中注入 IHubContext<ChatHub>
:
public class NotificationsHub : Hub
{
}
public class NotificationService(IHubContext<NotificationsHub> notificationsHub) : INotificationService
{
}
// ***** At Startup ********
// SignalR registration
private static void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR(routes =>
{
routes.MapHub<NotificationsHub>(hubRoute);
});
}
// dependencies registration
public static IServiceCollection RegisterServices(IServiceCollection services)
{
services.AddSingleton<INotificationsService, NotificationService>();
}
对你有用吗?
我正在使用 SignalR 3.0 开发 Asp .NET 3.1 应用程序,我需要能够随时访问 hubcontext。我定期接收数据并处理它,以便在计时器事件触发时将其推送给客户端。这意味着当客户端调用集线器方法或通过控制器或中间件时,我可以依赖访问集线器上下文的能力。由于我无法在此版本的 signalR 中使用 GlobalHost,因此最佳方法是什么?
我尝试了几种不同的方法,我最初想保留对 hubcontext 的静态引用,但我认为这不是一个非常可靠的方法。我想保留对 IServiceProvider
的静态引用,但是当我的计时器触发时,服务提供者已经被处理掉了。有什么建议吗?
如果您使用标准 Asp.Net 核心依赖注入 (IServiceCollection),您可以在服务的构造函数中注入 IHubContext<ChatHub>
:
public class NotificationsHub : Hub
{
}
public class NotificationService(IHubContext<NotificationsHub> notificationsHub) : INotificationService
{
}
// ***** At Startup ********
// SignalR registration
private static void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR(routes =>
{
routes.MapHub<NotificationsHub>(hubRoute);
});
}
// dependencies registration
public static IServiceCollection RegisterServices(IServiceCollection services)
{
services.AddSingleton<INotificationsService, NotificationService>();
}
对你有用吗?