我不得不说,不久前我偶然发现了类似的场景,我最终通过我的 Web API 和 signalR 共享了我的配置,但是您需要为 signalR 实现自定义生活方式,因为它不是基于 Web 请求。
特别是在 signalR 中,您会发现一些处理 Hub 中每个 Web 请求依赖项的问题,其中一些问题将为 null,例如 httpContext.Current 等。
解决方案:
您需要 WebRequestLifestlye 和 Lifestyle.Transient、Lifestyle.Singleton 或 LifetimeScopeLifestyle 之间的混合生活方式。我最终完成了装饰器模式的使用,你可以阅读这个post https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91还有这个post https://cuttingedge.it/blogs/steven/pivot/entry.php?id=92.
我的装饰师
public class CommandLifetimeScopeDecorator<T> : ICommandHandler<T>
{
private readonly Func<ICommandHandler<T>> _handlerFactory;
private readonly Container _container;
public CommandLifetimeScopeDecorator(
Func<ICommandHandler<T>> handlerFactory, Container container)
{
_handlerFactory = handlerFactory;
_container = container;
}
public void Handle(T command)
{
using (_container.BeginLifetimeScope())
{
var handler = _handlerFactory(); // resolve scoped dependencies
handler.Handle(command);
}
}
}
public interface ICommandHandler<in T>
{
void Handle(T command);
}
我使用 signalR 的集线器激活器管理依赖项
public class MyHubActivator : IHubActivator
{
private readonly Container _container;
public MyHubActivator(Container container)
{
_container = container;
}
public IHub Create(HubDescriptor descriptor)
{
return _container.GetInstance(descriptor.HubType) as IHub;
}
}
一个复合根文件,您将在其中处理依赖项
public CompositRoot(Container container)
{
_container = container;
}
public container Configure()
{
// _container.Registerall container dependencies
return _container;
}
然后在引导应用程序时共享您的复合根配置
var compositRoot = new CompositRoot(simpleInjector.Container); //simple injector instance
compositRoot.Configure();
对于信号R
GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => new MyHubActivator(compositRoot));
并且您可以在其他项目中重复使用您的配置!
我的两分钱
希望有帮助!