[英]Register multiple DbContext for IUnitOfWork using Unity IOC
我通過IUnitOfWork通過工作單元使用存儲庫模式
如果項目中有多個DbContext,並且需要注冊IUnitOfWork,如何在IoC中正確注冊? 例如,它似乎獲取了最后的注冊
Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample1DataContext>>(new ContainerControlledLifetimeManager());
Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample2DataContext>>(new ContainerControlledLifetimeManager());
當我解決時,它將始終返回我Sample2DataContext
https://github.com/ziyasal-archive/RepositoryT.EntityFramework/issues/11
Unity僅會讓您擁有一個“默認”映射。 如果希望將一個“從”類型( IUnitOfWork
)映射到多個“到”類型( EfUnitOfWork<Sample1DataContext>
, EfUnitOfWork<Sample2DataContext>
,...),那么您將需要使用命名注冊。
Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample1DataContext>>(
typeof(Sample1DataContext).Name, new ContainerControlledLifetimeManager());
Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample2DataContext>>(
typeof(Sample2DataContext).Name, new ContainerControlledLifetimeManager());
在這種情況下,我使用typeof(Sample1DataContext).Name
作為注冊名稱。
然后,在解析時,將需要使用注冊名稱來解析所需的具體類型。 例如,檢索EfUnitOfWork<Sample1DataContext>
:
Container.Resolve<IUnitOfWork>(typeof(Sample1DataContext).Name);
通常, IUnitOfWork
將是另一種類型(例如服務)的依賴項。 例如,要注冊一個映射到具體Service
且依賴於IUnitOfWork
的接口IService
,並且您希望使用EfUnitOfWork<Sample2DataContext>
類型,可以類似於以下內容進行注冊:
Container.RegisterType<IService, Service>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>(typeof(Sample2DataContext).Name)));
如果您需要為一個服務注入多個IUnitOfWork
實例,則只需將適當的參數添加到InjectionConstructor中即可。 因此,如果Service的構造函數是Service(IUnitOfWork data1Context, IUnitOfWork data2Context)
,則可以這樣做:
Container.RegisterType<IService, Service>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>(typeof(Sample1DataContext).Name)),
new ResolvedParameter<IUnitOfWork>(typeof(Sample2DataContext).Name)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.