SignalR中的简单喷油器注册问题 [英] Simple Injector registration problem in SignalR
问题描述
我在控制器中设置DI,如下所示,并绑定到注册IHubContext,如
I set DI in my Controller as shown below and tied to register IHubContext as it seen on
控制器:
Controller:
public class DemoController : Controller
{
private IHubContext<DemoHub> context;
public DemoController(IHubContext<DemoHub> context)
{
this.context = context;
}
}
Global.asax:
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?
But when I debug my app, encounter "System.ArgumentException: 'The given type IHubContext is not a concrete type. Please use one of the other overloads to register this type. Parameter name: TImplementation'" error. So, how can I register IHubContext properly?
推荐答案
由于ASP.NET MVC
尚未为SignalR
集线器上下文内置依赖注入,因此必须使用GlobalHost.ConnectionManager
获取上下文实例.这样,您可以在创建IHubContext
实例的容器中注册一个依赖项.考虑到您输入了中心
Since ASP.NET MVC
doesn't have built in dependency injection for SignalR
hub context you have to obtain a context instance using GlobalHost.ConnectionManager
. With this you can register a dependency with your container that creates IHubContext
instance. Considering you have typed hub
public class DemoHub : Hub<ITypedClient>
{
}
和界面
public interface ITypedClient
{
void Test();
}
注册依赖项如下
container.Register<IHubContext<ITypedClient>>(() =>
{
return GlobalHost.ConnectionManager.GetHubContext<DemoHub, ITypedClient>();
}, Lifestyle.Scoped);
控制器应该看起来像
public class DemoController : Controller
{
private IHubContext<ITypedClient> context;
public DemoController(IHubContext<ITypedClient> context)
{
this.context = context;
}
}
这篇关于SignalR中的简单喷油器注册问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!