繁体   English   中英

依赖注入到 SignalR 集线器(dotnet core 3.1)

[英]Dependency Injection into SignalR Hub (dotnet core 3.1)

我正在使用 SignalR 并且在让 DI 进入 SignalR 集线器时遇到问题。 我以为它会使用现有的 dotnet core DI 框架,但似乎并非如此。 我不断得到

System.InvalidOperationException: Unable to resolve service for type 'Comcast.Cs.Mercury.Web.Api.IHubClientHelper' while attempting to activate 'mercury_ms_auth.Hubs.AuthenticationHub'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubActivator`1.Create()
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection)
   at Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher`1.OnConnectedAsync(HubConnectionContext connection)
   at Microsoft.AspNetCore.SignalR.HubConnectionHandler`1.RunHubAsync(HubConnectionContext connection)

我注册了 singleton:

            services.AddSingleton<IHubClientHelper>(new HubClientHelper(loggerFactory.CreateLogger<HubClientHelper>())
            {
                ClientConnectionType = _environment.IsDevelopment()
                    ? ClientConnectionType.ConnectionId
                    : ClientConnectionType.UserId
            });

而且我有依赖进入集线器的构造函数:

public AuthenticationHub(TelemetryClient telemetryClient, IHubClientHelper clientHelper)
            : base(telemetryClient, clientHelper)
        {
            
        }

文档表明这应该有效。 有任何想法吗?

您的问题不是很清楚,但我将尝试回答您如何正确注册集线器并使用 DI 注入它。 首先,您在启动时添加集线器:

services.AddSignalR(hubOptions =>
{
    hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(hostConfiguration.SignalR.ClientTimeoutInterval);
    hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(hostConfiguration.SignalR.HandshakeTimeout);
    hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(hostConfiguration.SignalR.KeepAliveInterval);
    hubOptions.EnableDetailedErrors = hostConfiguration.SignalR.EnableDetailedErrors;
    hubOptions.MaximumReceiveMessageSize = hostConfiguration.SignalR.MaximumReceiveMessageSize;
    hubOptions.StreamBufferCapacity = hostConfiguration.SignalR.StreamBufferCapacity;
});
app.UseSignalR(routes =>
{
    routes.MapHub<YourHub>(/yourHub);
});

因此,这会将您的集线器添加为transient 然后你可以像这样注入你的集线器:

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

还有一些注意事项:

SignalR 期望为每条消息单独创建集线器。 如果您希望集线器处于 DI 中,则需要将其添加为瞬态服务。 您通常不应该将集线器从 DI 中解析出来。 如果您需要在 Hub 和其他一些组件之间共享代码,我建议使用 IHubContext 或将共享代码放在单独的 DI 服务中。

发现了问题。 我正在使用 Unity Container,结果发现该容器没有像 OOTB DI 框架那样自动注册 ILogger。 我通过使用 Immediate Window 尝试解决 IHubClientHelper 发现了这一点,它最终告诉我它无法解析 ILogger ( No public constructor is available for type Microsoft.Extensions.Logging.ILogger. )。 在快速谷歌之后,我找到了这个,并通过将以下内容添加到 Startup.cs 中的 ConfigureContainer 方法,我再次启动并运行。

var logFactory = new LoggerFactory();
container.AddExtension(new LoggingExtension(logFactory));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM