訣竅是將作用域生活方式之一傳遞到組合根的集中部分。你可以通過使用ScopedLifestyle
基類:
public static class BusinessLayerBootstrapper
{
public static void Bootstrap(Container container, ScopedLifestyle scopedLifestyle)
{
container.Register<IUnitOfWork, MyDbContext>(scopedLifestyle);
// etc...
}
}
在你的終端應用可以調用這個如下:使用Lifestyle
基類本身時
public class Global : Application
{
protected override Application_Start()
{
var container = new Container();
container.RegisterMvcControllers();
BusinessLayerBootstrapper.Bootstrap(container, new WebRequestLifestyle());
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
儘管這同樣的作品,這個類缺少一些您可能感興趣的功能,例如RegisterForDisposal
,GetCurrentScope
和WhenScopeEnds
。
薪火ScopedLifestyle
甚至還可以當您創建混合型的生活方式,因爲有一個Lifestyle.CreateHybrid
重載接受兩個ScopedLifestyle
實例,並返回一個新的ScopedLifestyle
實例:
ScopedLifestyle mixedScopeLifestyle = Lifestyle.CreateHybrid(
() => HttpContext.Current != null,
new WebRequestLifestyle(),
new LifetimeScopeLifestyle());