Search code examples
asp.net-coreasp.net-core-signalr

constructor with parameters in a signalr-core hub


I would like to inject something into my hub.

Basically I am trying to the equivalent of this tutorial https://learn.microsoft.com/en-us/aspnet/signalr/overview/advanced/dependency-injection, but for SignalR-Core. I am mostly interested in the part

public void Configuration(IAppBuilder app)
{
    GlobalHost.DependencyResolver.Register(
        typeof(ChatHub), 
        () => new ChatHub(new ChatMessageRepository()));

    App.MapSignalR();

    // ...
}

How do I do this Net Core and SignalR-Core?


Solution

  • Register your ChatMessageRepository in the DI container with:

    services.AddTransient(typeof(ChatMessageRepository), typeof(ChatMessageRepository));
    

    and then inject into your hub in the ctor:

    public ChatHub : Hub
    {
        private readonly ChatMessageRepository _repository;
        public ChatHub(ChatMessageRepository repository)
        {
            _repository = repository;
        }
        ...
    }