C# 使用Unity IOC为IUnitOfWork注册多个DbContext

C# 使用Unity IOC为IUnitOfWork注册多个DbContext,c#,entity-framework,entity-framework-6,unity-container,repository-pattern,C#,Entity Framework,Entity Framework 6,Unity Container,Repository Pattern,我正在使用存储库模式,工作单元使用IUnitOfWork via 国际奥委会注册样本如下所示 当您的项目中有多个DbContext,并且需要注册IUnitOfWork时,如何在IoC中正确注册?它似乎收到了最后一次注册 比如说 Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample1DataContext>>(new ContainerControlledLifetimeManager());

我正在使用存储库模式,工作单元使用IUnitOfWork via

国际奥委会注册样本如下所示

当您的项目中有多个DbContext,并且需要注册IUnitOfWork时,如何在IoC中正确注册?它似乎收到了最后一次注册 比如说

        Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample1DataContext>>(new ContainerControlledLifetimeManager());
        Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample2DataContext>>(new ContainerControlledLifetimeManager());
解析时,它将始终返回Sample2DataContext


Unity只允许您有一个默认映射。如果希望将一个类型从IUnitOfWork映射到多个类型EfUnitOfWork,EfUnitOfWork。。。然后您将需要使用命名注册

Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample1DataContext>>(
    typeof(Sample1DataContext).Name, new ContainerControlledLifetimeManager());
Container.RegisterType<IUnitOfWork, EfUnitOfWork<Sample2DataContext>>(
    typeof(Sample2DataContext).Name, new ContainerControlledLifetimeManager());
通常,IUnitOfWork是另一种类型(如服务)的依赖项。例如,要注册一个接口IService,该接口IService映射到一个具体的服务,并且它依赖于IUUnitOfWork,并且您希望使用EfUnitOfWork类型,您可以注册类似于:

Container.RegisterType<IService, Service>(
    new InjectionConstructor(
        new ResolvedParameter<IUnitOfWork>(typeof(Sample2DataContext).Name)));

当您解析什么时?如果我的服务类同时使用Datacontext呢?如果您在构造函数中使用IEnumerable alItems,您也可以获得所有实例。还有一个警告,我真的很喜欢unity IOC,但微软正在用它做Silverlight,它有点被抛弃了。因此,除非你正在创建一个Prism应用程序,否则我不建议你使用它。
Container.RegisterType<IService, Service>(
    new InjectionConstructor(
        new ResolvedParameter<IUnitOfWork>(typeof(Sample2DataContext).Name)));
Container.RegisterType<IService, Service>(
    new InjectionConstructor(
        new ResolvedParameter<IUnitOfWork>(typeof(Sample1DataContext).Name)),
        new ResolvedParameter<IUnitOfWork>(typeof(Sample2DataContext).Name)));