2014-10-08 59 views
1

我試圖爲由多個應用程序和幾個類庫組成的解決方案實現組合根。我使用Simple Injector作爲我選擇的DI框架。使用簡單噴油器在應用程序特定基礎上重寫生命週期

具有多個應用程序需要多個組合根。但是,我不想在每個組合根目錄中都有重複的容器註冊。因此,我正在考慮使用https://stackoverflow.com/a/11993030/852765中提到的方法,但遇到了問題。

如何在應用基礎上覆蓋註冊的生命週期?具體來說,我想覆蓋一些容器註冊,以在我的Web API應用程序中擁有「每個Web API請求生命週期」,而我的其他應用程序使用臨時生命週期進行相同的註冊。

回答

2

訣竅是將作用域生活方式之一傳遞到組合根的集中部分。你可以通過使用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,GetCurrentScopeWhenScopeEnds

薪火ScopedLifestyle甚至還可以當您創建混合型的生活方式,因爲有一個Lifestyle.CreateHybrid重載接受兩個ScopedLifestyle實例,並返回一個新的ScopedLifestyle實例:

ScopedLifestyle mixedScopeLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null, 
    new WebRequestLifestyle(), 
    new LifetimeScopeLifestyle()); 
相關問題