Search code examples
asp.netasp.net-coredependency-injectionsignalrasp.net-core-signalr

ASP.NET Core SignalR Dependency Injection in OnConnectedAsync


I have created a service like so: builder.Services.AddSingleton<ISessionManagerService, SessionManagerService>(); and can create new methods in my Hub with it as a parameter, like so:

public async Task Send(string action, object args, ISessionManagerService sessionManager)
{
    await Clients.All.Receive(action, args);
}

However, when I override OnConnectedAsync, I cannot add an ISessionManagerService as a parameter. I have tried OnConnectedAsync(ISessionManagerService sessionManager) and OnConnectedAsync([FromServices] ISessionManagerService sessionManager), neither of which works (the error is "no suitable method found to override").

What is the proper way to access my service in the OnConnectedAsync method?


Solution

  • DI for OnConnectedAsync can be done in the Hub constructor. For example:

    private ISessionManagerService sessionManager;
    
    public MiddlewareHub(ISessionManagerService sessionManager)
    {
        this.sessionManager = sessionManager;
    }
    

    While this method works, it's not as clean and easy as what can be done for new methods in the Hub. If anyone has a better method, please share it.