Search code examples
c#.netdependency-injectionsignalr

Is there a way to achieve Dependency Injection within the constructor of a SignalR Hub?


Good day all, in my SignalR Hub on my ASP.NET MVC Application i am trying to inject a "NotificationService" class into the constructor of my SignalR Hub.

public class ManualReconHub : Hub<IManualReconHub>
{
    private INotificationService _notificationService;
    public static IList<string> AllDisabledRows = new List<string>();
    public static IList<string> AllNotifications = new List<string>();

    public ManualReconHub(INotificationService notificationService)
    {
        _notificationService = notificationService;
    }

This is of course breaking the connection because the constructor for the hub is expecting no parameteres, according to what ive read in the docs. Is there a way to achieve this the way i am trying to, or is the only way to inject a class into a hub via the following method in the docs:

GlobalHost.DependencyResolver.Register(
        typeof(ChatHub), 
        () => new ChatHub(new ChatMessageRepository()));

I am not familiar with this method of dependency injection, and would prefer to use dependency injection through my application in the same manner. I am the following in my Program.cs at the moment:

builder.Services.AddScoped<IServiceCollection, ServiceCollection>();

Any help on the issue would be greatly appreciated!


Solution

  • You have used an old deprecated version of SignalR

    in .NET Core SignalR is included. You add it by doing

    services.AddSignalR();
    

    You can then define the hub like

    app.UseEndpoints(config => config.MapHub<ManualReconHub>("/ManualReconHub"));
    

    You can also use a library like SignalR.EventAggregatorProxy todo the heavy lifting for you.

    https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

    Disclamier: I am the author of said library