【发布时间】:2023-03-06 21:26:02
【问题描述】:
我完全按照 MS 规则定义了我的强类型 SignalR 集线器
public class OutputMessages : Hub<IOutputMessages>
{...}
以同样的方式将我的 SignalR 集线器注入到控制器
public class ApplicationAPIController : ControllerBase
{
public ApplicationAPIController(IHubContext<OutputMessages, IOutputMessages> _outputMessages)
{...}
}
在启动中我将 SignalR 服务添加为
services.AddSignalR()
.AddHubOptions<OutputMessages>(options =>
{
options.EnableDetailedErrors = true;
})
并定义端点
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<OutputMessages>("/OutputMessages", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
});
看起来不错?是的。而且编译很好。但在运行时我收到
fail: Microsoft.AspNetCore.SignalR.HubConnectionHandler[1]
Error when dispatching 'OnConnectedAsync' on hub.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.SignalR.Hub`1[IOutputMessages]' while attempting to activate 'OutputMessages'.
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)
dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[6]
OnConnectedAsync ending.
【问题讨论】:
-
我不认为
.AddHubOptions<OutputMessages>(options =>...是正确的。将其更改为services.AddSignalR(o => o.EnableDetailedErrors = true);,然后尝试注入IOutputMessages正常路线:services.AddTransient<IOutputMessages, OutputMessages>(); -
在这种情况下,我在项目初始化中收到 - '某些服务无法构建(验证服务描述符时出错'ServiceType:IOutputMessages Lifetime:Transient ImplementationType:OutputMessages':无法解析服务在尝试激活“OutputMessages”时键入“Microsoft.AspNetCore.SignalR.Hub`1[IOutputMessages]”。)”
-
问题是你的集线器方法中有一个构造函数到你的
OutputMessages类。您不需要任何构造函数,因为AddSignalR在 DI 上注册了 HUB。然后,您通过 DI 解决的依赖关系就像我在之前的问题中回答的那样。
标签: asp.net-core dependency-injection signalr