在ASP.NET Core中实例化IHubContext

问题描述 投票:0回答:1

我正在Web项目的不同位置上使用SignalR。在我的Controllers和HostedService中,这似乎工作正常。客户端实例化与我的集线器的连接,我可以使用注入到每个控制器/托管服务的构造函数中的IHubContext实例与它们进行通讯。

我有另一个单例,在后台运行(没有HosteService或BackgroundTask)。此类也将IHubContext注入构造函数中。仍然每次调用它时,似乎此单例都具有IHubContext的不同实例,因为此上下文没有与其连接的客户端/组。

此类已在启动功能中注册为此类:

services.AddSingleton<IServiceEventHandler<TourMonitorEvent>, TourMonitorEventHandler>();

要配置SignalR,我在ConfigureServices中执行以下操作:

services.AddSignalR().AddNewtonsoftJsonProtocol();

以及以下配置:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<MyHubClass>("/hubEndpoint");
    endpoints.MapControllers();
});

将IHubContext ist注入到Controllers / Hostedservices和单例中,如下所示:

public class MySingleton : IHandler<SomeGenericClass>
{
    private readonly IHubContext<MyHubClass> _hubContext;

    public MySingleton(IHubContext<MyHubClass> hubContext)
    {
        _hubContext = hubContext;
    } 
}

Controllers / HosteService的实例化与我的Singleton是否有所不同,是否会影响IHubContext实例化?

asp.net-core singleton signalr instantiation
1个回答
0
投票

documentation中所述:

集线器是瞬态的。

因此,由于您Singleton不是HostedService或BackgroundTask,所以我建议使用DI注入集线器。

private IHubContext<MyHubClass, IMyHubClass> MyHubClass
{
    get
    {
        return this.serviceProvider.GetRequiredService<IHubContext<MyHubClass, IMyHubClass>>();
    }
}

尝试一下,验证上下文是否现在符合您的期望。

© www.soinside.com 2019 - 2024. All rights reserved.