我在 Controller 中设置 DI,如下所示,并绑定(bind)到注册 IHubContext,如上所示
Controller :
public class DemoController : Controller
{
private IHubContext<DemoHub> context;
public DemoController(IHubContext<DemoHub> context)
{
this.context = context;
}
}
Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.Register<IHubContext, IHubContext>(Lifestyle.Scoped);
// or
container.Register<IHubContext>(Lifestyle.Scoped);
// code omitted
}
但是当我调试我的应用程序时,遇到“System.ArgumentException:'给定类型 IHubContext 不是具体类型。请使用其他重载之一来注册此类型。参数名称:TImplementation””错误。那么,如何正确注册IHubContext呢?
最佳答案
自 ASP.NET MVC
没有 SignalR
的内置依赖注入(inject)hub 上下文,您必须使用 GlobalHost.ConnectionManager
获取上下文实例。这样,您就可以向容器注册一个依赖项,创建 IHubContext
实例。考虑到您已输入 hub
public class DemoHub : Hub<ITypedClient>
{
}
和界面
public interface ITypedClient
{
void Test();
}
注册依赖项如下
container.Register<IHubContext<ITypedClient>>(() =>
{
return GlobalHost.ConnectionManager.GetHubContext<DemoHub, ITypedClient>();
}, Lifestyle.Scoped);
Controller 应该看起来像
public class DemoController : Controller
{
private IHubContext<ITypedClient> context;
public DemoController(IHubContext<ITypedClient> context)
{
this.context = context;
}
}
关于c# - SignalR 中的简单注入(inject)器注册问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57256906/