0

我在我的業務層級別(簡化代碼)以下等級:團結子容器HierarchicalLifetimeManager MVC和Windows服務

public class StatusUpdater : IStatusUpdater 
{ 
    private readonly IStatusRepo _statusRepo; 

    public class StatusUpdater(IStatusRepo statusRepo) 
    { 
     _statusRepo = statusRepo; 
    } 

    public voic UpdateStatus(int id, string newStatus) 
    { 
     _statusRepo.UpdateStatus(id,newStatus); 
    } 
} 

所以目前在MVC方面我使用PerRequestLifetimeManager來控制壽命的DbContext

但現在在窗口服務,我不能使用的,所以我要做到以下幾點,但它不正確的感覺,因爲它看起來很像服務定位

using(var container = ConfiguredContainer.CreateChildContainer()) 
{ 
    var statusUpdater = container.Resolve<IStatusUpdater>(); 
    statusUpdater.UpdateStatus("test"); 
} 

還有其他選擇嗎?並且在那裏使用在MVC應用中的相同的代碼和窗口服務,而不必2種類型的註冊的一種方法:

MVC:

container.RegisterType<IStatusRepo, StatusRepo>(new PerRequestLifetimeManager()); 

WindowsService:

container.RegisterType<IStatusRepo, StatusRepo>(new HierarchicalLifetimeManager()); 
+0

不確定'Unity',但是在其他DI框架中,無論如何您都必須爲'MVC'和'Win Service'使用不同的註冊碼。直接調用「Resolve」方法總是會「聞到」,因爲這是DI框架的要求 - 在需要時解析實例。當我們在代碼中調用'.Resolve'方法時,意味着我們很可能做錯了什麼。我們可以在構造函數中注入實例,並改變使用它們的對象的生命範圍。 – Fabjan

回答

0

我通常註冊我的類型在他們自己的程序集中,很可能和你一樣,但是當執行程序集有特定的東西時,我會在執行程序集的註冊中重寫它。

// In BusinessProcessor 
container.RegisterType<IBusinessProcessorA, MyBusinessProcessorA1>(); 
container.RegisterType<IBusinessProcessorA, MyBusinessProcessorA2>(); 
container.RegisterType<IBusinessProcessorB, MyBusinessProcessorB1>(); 

// In DataAccessLayer 
container.RegisterType<IRepository, Repository<A>>("A", new HierarchicalLifetimeManager()); 
container.RegisterType<IRepository, Repository<B>>("B", new HierarchicalLifetimeManager()); 
container.RegisterType<IRepository, Repository<C>>("C", new HierarchicalLifetimeManager()); 

// In WindowsService 
Register(BusinessProcessor); // Call to have the BusinessProcessor register it's own things. 
Register(DataAccessLayer);  // Call to have the DataAccessLayer register it's own things. 
container.RegisterType<IService, MyService>(); 

// In WebApplication 
Register(BusinessProcessor); // Call to have the BusinessProcessor register it's own things. 
Register(DataAccessLayer);  // Call to have the DataAccessLayer register it's own things. 
container.RegisterType<IController, MyController>(); 
container.RegisterType<IRepository, Repository<A>>("A", new PerRequestLifetimeManager()); 

另一種方式可能是註冊庫,在DAL,用不同的命名註冊,併爲BusinessProcessors這樣做,但是這將意味着你的整體解決方案知道這一事實,我不會推薦。完全一樣。