根据这篇文章,应该可以将每个Web请求依赖项注入SignalR集线器(尽管有一些限制,如OnDisconnected()方法的问题).在我的例子中,它是ASP Web API(而不是MVC),并且由于某种原因它不起作用.
以下是相关部分:
container.RegisterWebApiControllers(httpConfiguration);
container.RegisterWebApiRequest<DbContext, MyDbContext>();
container.RegisterWebApiRequest<ISampleRepository, SampleRepository>(); //DbContext injected to SampleRepository
//Enable injections to SignalR Hubs
var activator = new SimpleInjectorHubActivator(container);
GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => activator);
Run Code Online (Sandbox Code Playgroud)
这个类可以注入集线器:
public class SimpleInjectorHubActivator : IHubActivator
{
private readonly Container _container;
public SimpleInjectorHubActivator(Container container)
{
_container = container;
}
public IHub Create(HubDescriptor descriptor)
{
return (IHub)_container.GetInstance(descriptor.HubType);
}
}
Run Code Online (Sandbox Code Playgroud)
和Hub本身:
[HubName("sample")]
public class SampleHub : Hub
{
public ActiveBetsHub(ISampleRepository repository)
{
}
//Irrelevant methods here. OnDisconnected() NOT implemented!
}
Run Code Online (Sandbox Code Playgroud)
通过此设置,我得到例外:
No registration …Run Code Online (Sandbox Code Playgroud)