[英]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.