依赖注入到SignalR Hubdotnet core 3.1

问题描述

我正在使用SignalR,让DI进入SignalR集线器时遇到了问题。我以为它将使用现有的dotnet核心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)

注册了单身人士:

            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中,则需要将其添加为Transient服务。通常,您不应该用DI解决集线器。如果需要在集线器和其他组件之间共享代码,建议使用IHubContext或将共享代码放在单独的DI服务中。

,

发现了问题。我正在使用Unity Container,结果是该容器没有像OOTB DI框架那样自动注册ILogger。我发现使用即时窗口尝试解析IHubClientHelper最终发现了它无法解析ILogger(No public constructor is available for type Microsoft.Extensions.Logging.ILogger.)。快速浏览一下之后,我发现了this,并将以下内容添加到Startup.cs的ConfigureContainer方法中,就重新启动并运行。

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