Search code examples
c#asp.net-mvcdependency-injectionsignalr

SignalR : How to use IHubContext<THub,T> Interface in ASP.NET MVC?


I have been trying to used the following approach in my ASP.NET MVC project where Microsoft.AspNet.SignalR library is used:

public interface ITypedHubClient
{
  Task BroadcastMessage(string name, string message);
}

Inherit from Hub:

public class ChatHub : Hub<ITypedHubClient>
{
  public void Send(string name, string message)
  {
    Clients.All.BroadcastMessage(name, message);
  }
}

Inject your the typed hubcontext into your controller, and work with it:

public class DemoController : Controller
{   
  IHubContext<ChatHub, ITypedHubClient> _chatHubContext;

  public DemoController(IHubContext<ChatHub, ITypedHubClient> chatHubContext)
  {
    _chatHubContext = chatHubContext;
  }

  public IEnumerable<string> Get()
  {
    _chatHubContext.Clients.All.BroadcastMessage("test", "test");
    return new string[] { "value1", "value2" };
  }
}

However, there is no IHubContext<THub,T> Interface in Microsoft.AspNet.SignalR library and I for this reason I cannot use IHubContext with two parameters (IHubContext<ChatHub, ITypedHubClient> _chatHubContext;). So, I am wondering if it is possible to a DI library or method. If so, how to fix this problem?


Solution

  • Microsoft.AspNetCore.SignalR contains IHubContext for untyped hub

    public interface IHubContext<THub> where THub : Hub
    {
        IHubClients Clients { get; }
        IGroupManager Groups { get; }
    }
    

    and for typed hub

    public interface IHubContext<THub, T> where THub : Hub<T> where T : class
    {
        IHubClients<T> Clients { get; }
        IGroupManager Groups { get; }
    }
    

    As you can see from declarations the THub parameter isn't used anywhere and in fact it exists for dependency injection purposes only.

    Microsoft.AspNet.SignalR in it's turn contains the following IHubContext declarations

    // for untyped hub
    public interface IHubContext
    {
        IHubConnectionContext<dynamic> Clients { get; }
        IGroupManager Groups { get; }
    }
    
    // for typed hub
    public interface IHubContext<T>
    {
        IHubConnectionContext<T> Clients { get; }
        IGroupManager Groups { get; }
    }
    

    As you can see in this case the interfaces don't contain THub parameter and it's not needed because ASP.NET MVC doesn't have built in DI for SignalR. For using typed client it's sufficient to use IHubContext<T> in your case. To use DI you have to "manually inject" hub context as I described it here.