【发布时间】:2020-07-01 13:42:41
【问题描述】:
我在我的 Web 项目的不同位置使用 SignalR。在我的 Controllers 和 HostedService 中,这似乎工作正常。客户端实例化与我的集线器的连接,我可以使用 IHubContext 实例与它们进行通信,该实例注入每个控制器/托管服务的构造函数中。
我有另一个单例,在后台运行(没有 HosteService 或 BackgroundTask)。此类也将 IHubContext 注入到构造函数中。仍然每次调用它时,似乎这个单例都有一个不同的 IHubContext 实例,因为这个上下文没有连接到它的客户端/组。
这个类在启动函数中被注册为this:
services.AddSingleton<IServiceEventHandler<TourMonitorEvent>, TourMonitorEventHandler>();
要配置 SignalR,我在 ConfigureServices 中执行以下操作:
services.AddSignalR().AddNewtonsoftJsonProtocol();
以及配置中的以下内容:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHubClass>("/hubEndpoint");
endpoints.MapControllers();
});
IHubContext 在 Controllers/Hostedservices 和单例中注入如下:
public class MySingleton : IHandler<SomeGenericClass>
{
private readonly IHubContext<MyHubClass> _hubContext;
public MySingleton(IHubContext<MyHubClass> hubContext)
{
_hubContext = hubContext;
}
}
Controllers/HosteService 的实例化方式是否与我的 Singleton 不同,可能会影响 IHubContext 的实例化?
【问题讨论】:
-
请提供您如何注入 IHubContext 的代码;)
-
@Kiril1512 我已经编辑回答,添加了IHubContext的注入
标签: asp.net-core singleton signalr instantiation