我正在使用 Simple Injector 作为我的 IoC 容器,并采用以下技术来为某些对象注册“混合”生活方式,无论是按 Web 请求还是每个线程。
interface IUnitOfWork { }
interface IWebUnitOfWork : IUnitOfWork { }
interface IThreadUnitOfWork : IUnitOfWork { }
class UnitOfWork : IWebUnitOfWork, IThreadUnitOfWork { }
container.RegisterPerWebRequest<IWebUnitOfWork, UnitOfWork>();
container.RegisterLifetimeScope<IThreadUnitOfWork, UnitOfWork>();
container.Register<IUnitOfWork>(() => container.GetInstance<UnitOfWork>());
// Register as hybrid PerWebRequest / PerLifetimeScope.
container.Register<UnitOfWork>(() =>
{
if (HttpContext.Current != null)
return container.GetInstance<IWebUnitOfWork>() as UnitOfWork;
else
return container.GetInstance<IThreadUnitOfWork>() as UnitOfWork;
});
我对这个解决方案并不完全满意,因为对于每个要求,我必须定义额外的空接口以使其工作并确保它们被我的具体类引用。
有什么理由我不应该使用以下扩展方法而不是定义额外的接口?如果这些方法存在问题,是否有其他方法可以完全确定我当前的容器实例正在 IIS 中运行?
public static void RegisterHybridLifestyle<TService, TImplementation>(
this Container container)
where TService : class
where TImplementation : class, TService
{
if (System.Web.Hosting.HostingEnvironment.ApplicationHost != null)
container.RegisterPerWebRequest<TService, TImplementation>();
else
container.RegisterLifetimeScope<TService, TImplementation>();
}
public static void RegisterForLifestyle<TConcrete>(
this Container container)
where TConcrete : class
{
if (HostingEnvironment.ApplicationHost != null)
container.RegisterPerWebRequest<TConcrete>();
else
container.RegisterLifetimeScope<TConcrete>();
}
更新
上述问题和后续问题是基于对 SimpleInjector 和混合注册的误解。上面和 SO 其他地方描述的技术适用于容器可以为 Web 请求和不在 Web 请求上下文中运行的后台进程的请求提供服务的情况。我一直在尝试实现的是变量注册,以适应适用于 Web 请求或的容器的配置线程请求的容器配置。即我需要将我的容器配置为在 IIS 中工作并在 Windows 服务中工作。我不需要可以同时满足两者的动态注册。
结果是以下扩展方法,我从我的解决方案中删除了“额外”接口:-)
public static void RegisterForScope<TService, TImplementation>(this Container container)
where TService : class
where TImplementation : class, TService
{
if (System.Web.Hosting.HostingEnvironment.ApplicationHost != null)
container.RegisterPerWebRequest<TService, TImplementation>();
else
container.RegisterLifetimeScope<TService, TImplementation>();
}
public static void RegisterForScope<TConcrete>(this Container container)
where TConcrete : class
{
if (System.Web.Hosting.HostingEnvironment.ApplicationHost != null)
container.RegisterPerWebRequest<TConcrete>();
else
container.RegisterLifetimeScope<TConcrete>();
}