根据this帖子,应该可以将每个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);
这个类可以注入集线器:
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);
}
}
和Hub本身:
[HubName("sample")]
public class SampleHub : Hub
{
public ActiveBetsHub(ISampleRepository repository)
{
}
//Irrelevant methods here. OnDisconnected() NOT implemented!
}
通过此设置,我得到例外:
No registration for type SampleHub could be found and
an implicit registration could not be made.
The ISampleRepository is registered as 'Web API Request'
lifestyle, but the instance is requested outside the context of a Web API Request.
据我所知,这是预期的。但是,当我将存储库的生活方式更改为Transient时,我得到了完全相同的异常:
var transientHybrid = Lifestyle.CreateHybrid(() => HttpContext.Current != null, new WebApiRequestLifestyle(), Lifestyle.Transient);
container.Register<ISampleRepository, SampleRepository>(transientHybrid);
我怀疑问题可能在于HttpContext.Current != null
检查不适用于Web API的方式与MVC相同。
SignalR 2.2
Simple Injector 2.8.3
我想念什么?
更新
这是关于SignalR如何创建Hubs的堆栈跟踪:
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.Container.GetInstance(Type serviceType)
at MyWebAbi.WebApiApplication.SimpleInjectorHubActivator.Create(HubDescriptor descriptor) in Global.asax.cs:line 108
at Microsoft.AspNet.SignalR.Hubs.DefaultHubManager.ResolveHub(String hubName)
at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.CreateHub(IRequest request, HubDescriptor descriptor, String connectionId, StateChangeTracker tracker, Boolean throwIfFailedToCreate)
因此,正确的解决方案是将ExecutionContextScope
用于集线器,但需要明确关闭此范围,这会使事情变得更复杂......
答案 0 :(得分:7)
您对混合生活方式的定义不正确。 WebApiRequestLifestyle
HttpContext
不依赖于HttpContext.Current != null
,因此请检查container.GetCurrentExecutionContextScope()
是否无效。您必须通过调用var transientHybrid = Lifestyle.CreateHybrid(
() => container.GetCurrentExecutionContextScope() != null,
new WebApiRequestLifestyle(),
Lifestyle.Transient);
来检查是否存在活动的Web API请求生活方式范围(或执行上下文范围,基本相同):
MyDbContext
请注意,你应该非常小心构成一个混乱的生活方式和短暂的生活方式,因为这很容易产生错误的结果。这实际上是某些DI库的默认行为,但这是一个design flaw IMO。我假设您非常有意识地使用范围生活方式注册了您的Transient
,因为您需要确保在整个请求中使用相同的实例。使用MyDbContext
生活方式意味着您可以在请求期间获得多个MyDbContext
。这可能不是问题,因为在您的集线器中,您当前可能只有一个对MyDbContext
的引用,但是一旦您的对象图更改并且添加了对WebApiRequestLifestyle
的第二个引用,您的代码可能会中断。< / p>
相反,我建议不要使用这种生活方式的组合。相反,只需使用ExecutionContextScopeLifestyle
或{{1}}(它们是相同的),并确保在解决集线器之前启动此类执行上下文范围。
顺便说一句,不要忘记在Simple Injector中明确注册您的集线器。这允许Simple Injector为您分析完整的对象图,包括您的集线器类。
答案 1 :(得分:3)
最近我遇到了同样的问题,发现以下情况很好,希望这会对某人有所帮助:
public class SignalRDependencyResolver : DefaultDependencyResolver
{
public SignalRDependencyResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override object GetService(Type serviceType)
{
return _serviceProvider.GetService(serviceType) ?? base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var @this = (IEnumerable<object>) _serviceProvider.GetService(typeof (IEnumerable<>).MakeGenericType(serviceType));
var @base = base.GetServices(serviceType);
return @this == null ? @base : @base == null ? @this : @this.Concat(@base);
}
private readonly IServiceProvider _serviceProvider;
}
public class SignalRHubDispatcher : HubDispatcher
{
public SignalRHubDispatcher(Container container, HubConfiguration configuration) : base(configuration)
{
_container = container;
}
protected override Task OnConnected(IRequest request, string connectionId)
{
return Invoke(() => base.OnConnected(request, connectionId));
}
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Invoke(() => base.OnReceived(request, connectionId, data));
}
protected override Task OnDisconnected(IRequest request, string connectionId, bool stopCalled)
{
return Invoke(() => base.OnDisconnected(request, connectionId, stopCalled));
}
protected override Task OnReconnected(IRequest request, string connectionId)
{
return Invoke(() => base.OnReconnected(request, connectionId));
}
private async Task Invoke(Func<Task> method)
{
using (_container.BeginExecutionContextScope())
await method();
}
private readonly Container _container;
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
container.Register<DbContext, MyDbContext>(Lifestyle.Scoped);
container.Register<ISampleRepository, SampleRepository>(Lifestyle.Scoped);
// if you want to use the same container in WebApi don't forget to add
app.Use(async (context, next) => {
using (container.BeginExecutionContextScope())
await next();
});
// ... configure web api
var config = new HubConfiguration
{
Resolver = new SignalRDependencyResolver(container)
}
// ... configure the rest of SignalR
// pass SignalRHubDispatcher
app.MapSignalR<SignalRHubDispatcher>("/signalr", config);
}
}