本文介绍了SignalR:如何使用IHubContext< THub,T>. ASP.NET MVC中的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在使用Microsoft.AspNet.SignalR库的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);
}

从集线器继承

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

将类型化的hubcontext注入到控制器中,并对其进行处理:

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

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

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?

推荐答案

Microsoft.AspNetCore.SignalR包含IHubContext(用于无类型的集线器)

Microsoft.AspNetCore.SignalR contains IHubContext for untyped hub

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参数没有在任何地方使用,实际上它仅用于依赖项注入.

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依次包含以下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,您必须在此处手动注入"我所描述的中心上下文.

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.

这篇关于SignalR:如何使用IHubContext&lt; THub,T&gt;. ASP.NET MVC中的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:31