我有很多Hub并注册它们:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<FinanceHub>("/hub/finance");
endpoints.MapHub<PartnersHub>("/hub/partners");
...
endpoints.MapHub<WarehousesHub>("/hub/warehouses");
endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}");
});
我注册SignalR:
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
options.MaximumReceiveMessageSize = signalrMaxMessageLimit * 8192;
}).AddMessagePackProtocol(conf =>
{
conf.FormatterResolvers.Clear();
conf.FormatterResolvers.Add(CircularResolver.Instance);
});
它们作为 SignalR 集线器工作。但是当我尝试在 Microsoft.AspNetCore.Mvc.ControllerBase 中解决它们时:
private IHubContext<FinanceHub> financeHub => provider.GetRequiredService<IHubContext<FinanceHub>>();
public PaymentRegisterController(
ILogger<ServiceController> logger,
IServiceProvider _provider) : base(logger)
{
provider = _provider;
}
我得到一个例外:
System.InvalidOperationException: No service for type 'Microsoft.AspNet.SignalR.IHubContext`1[Engy.Plantain.Procurement.Backend.Hubs.FinanceHub]' 已注册
问题在哪里?
作为每个人,我敢肯定,认为,这是我的错误。在 API 控制器中,我试图解析 Microsoft.AspNet.SignalR.IHubContext 而不是 Microsoft.AspNetCore.SignalR.IHubContext。 现在一切正常。
我认为在
.NET 6
中做到这一点的新方法
你可以有多个解析器
services.AddSignalR()
.AddMessagePackProtocol(options =>
{
options.SerializerOptions = MessagePackSerializerOptions.Standard
.WithResolver(MessagePack.Resolvers.StandardResolver.Instance)
.WithResolver(MessagePack.Resolvers.NativeDateTimeResolver.Instance)
.WithSecurity(MessagePackSecurity.UntrustedData);
});