asp.net-coredependency-injectionbackground-serviceasp.net-core-signalr

Injecting IHubContext into my background service for SignalR in .NET 5


i have a hub class

       public class MyHub : Hub {
    private readonly AppDbContext _dbContext;
       
    public MyHub(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public override Task OnConnectedAsync()
    {
        // Implementation
    }
}

when i try to inject Ihubcontext and run the app i get: unable to resolve service for type Microsoft.AspNet.SignalR.IHubContex

public class NotificationService : BackgroundService
{
private readonly IHubContext<MyHub> _hubContext;
private readonly AppDbContext _dbContext;
private int lastProcessedNotificationId = 0;
public NotificationService(IHubContext<MyHub> hubContext, AppDbContext dbContext)
{
_dbContext = dbContext;
_hubContext=hubContext;

        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
              
                await _hubContext.Clients.All.SendMessageToAll("Test");
    
            }
        }
    }

i expect to be injected like in my controller it works


Solution

  • You are using wrong package. In your project, you should use Microsoft.AspNetCore.SignalR package, instead of Microsoft.AspNet.SignalR.

    You need to uninstall the Microsoft.AspNet.SignalR package, since signalr is build-in feature in asp.net core. You don't need to add any packages. You can use it like below in the .cs file namespace.

    using Microsoft.AspNetCore.SignalR;
    

    And for J.Memisevic's comment, we want to check how you register the background service.

    Something like

    builder.Services.AddHostedService<NotificationService>();