我在我的网络项目的不同地方使用SignalR。在我的控制器和HostedService中,这似乎工作得很好。客户端实例化与我的集线器的连接,我可以使用IHubContext实例与它们进行通信,该实例被注入到每个控制器/hostedservice的构造函数中。
我有另一个单例,在后台运行(没有HosteService或BackgroundTask)。这个类也会在构造函数中注入IHubContext。然而,每次调用它时,这个单例似乎都有一个不同的IHubContext实例,因为这个上下文没有连接到它的客户机/组。
这个类在启动函数中注册如下:
services.AddSingleton<IServiceEventHandler<TourMonitorEvent>, TourMonitorEventHandler>();
为了配置SignalR,我在ConfigureServices中执行以下操作:
services.AddSignalR().AddNewtonsoftJsonProtocol();
以及配置中的下列内容:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHubClass>("/hubEndpoint");
endpoints.MapControllers();
});
在控制器/Hostedservices和单例中注入的IHubContext ist如下:
public class MySingleton : IHandler<SomeGenericClass>
{
private readonly IHubContext<MyHubClass> _hubContext;
public MySingleton(IHubContext<MyHubClass> hubContext)
{
_hubContext = hubContext;
}
}
控制器/HosteService的实例化方式是否与我的Singleton不同,可能会影响IHubContext实例化?
发布于 2020-03-20 07:21:04
正如文档中所说的
枢纽是短暂的。
因此,由于Singleton不是HostedService或BackgroundTask,所以我建议使用DI注入集线器。
private IHubContext<MyHubClass, IMyHubClass> MyHubClass
{
get
{
return this.serviceProvider.GetRequiredService<IHubContext<MyHubClass, IMyHubClass>>();
}
}
尝试这样做,并验证当前的上下文是否与您预期的一样。
https://stackoverflow.com/questions/60773834
复制相似问题