简体   繁体   中英

How to get SignalR IHubContext from DI in .NET Core 3.1?

I have many Hubs and register them:

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?}");
});

I register SignalR:

services.AddSignalR(options =>
{
    options.EnableDetailedErrors = true;
    options.MaximumReceiveMessageSize = signalrMaxMessageLimit * 8192;
}).AddMessagePackProtocol(conf =>
{
    conf.FormatterResolvers.Clear();
    conf.FormatterResolvers.Add(CircularResolver.Instance);
});

They work as SignalR hubs. But when I try to resolve them in Microsoft.AspNetCore.Mvc.ControllerBase:

private IHubContext<FinanceHub> financeHub => provider.GetRequiredService<IHubContext<FinanceHub>>();

public PaymentRegisterController(
    ILogger<ServiceController> logger,
    IServiceProvider _provider) : base(logger)
{
    provider = _provider;
}

I get an exception:

System.InvalidOperationException: No service for type 'Microsoft.AspNet.SignalR.IHubContext`1[Engy.Plantain.Procurement.Backend.Hubs.FinanceHub]' has been registered.

Where is the problem?

As eveyone, I am sure, thought, it was my mistake. In the API-controller I was trying to resolve Microsoft.AspNet.SignalR.IHubContext instead of Microsoft.AspNetCore.SignalR.IHubContext . Now everything works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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