SignalR:如何在 ASP.NET MVC中使用IHubContext<THub,T>接口?



我一直在尝试在 ASP.NET MVC项目中使用以下方法,其中使用了Microsoft.AspNet.SignalR库:

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

从中心继承:

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

将您作为类型化的 hubcontext 注入到控制器中,并使用它:

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" };
  }
}

但是,Microsoft.AspNet.SignalR库中没有IHubContext<THub,T>接口,因此我不能将IHubContext与两个参数一起使用(IHubContext<ChatHub, ITypedHubClient> _chatHubContext;(。所以,我想知道是否可以使用 DI 库或方法。如果是这样,如何解决此问题?

Microsoft.AspNetCore.SignalR包含非类型化集线器的IHubContext

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

和类型化集线器

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

从声明中可以看出,THub 参数没有在任何地方使用,实际上它仅用于依赖项注入目的。

Microsoft.AspNet.SignalR依次包含以下IHubContext声明

// 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; }
}

正如您在这种情况下所看到的,接口不包含THub参数,并且不需要它,因为ASP.NET MVC没有内置用于SignalR的 DI。对于使用类型化客户端,在您的情况下使用 IHubContext<T> 就足够了。若要使用 DI,必须"手动注入"中心上下文,如我在此处所述。

controller中对我有用的是

private readonly IHubContext<MsgHub,IMsgHub> HubContext;
public MyController(IHubContext<MsgHub, IMsgHub> context)
{
    HubContext = context;
}

相关内容

最新更新