使用Unity 3注册集合的更清洁方式

时间:2014-04-11 14:42:17

标签: inversion-of-control unity-container ioc-container

我通常使用Autofac但这个客户端要求我们在他们的项目中使用Unity。通过匹配接口注册的能力很好,并且从我不得不使用版本2开始节省了一些时间。我仍然发现集合有点精简。是否有一种技术可以让我能够添加新的IPrePopulationModule实例而无需像我必须单独注册它们一样?

    container.RegisterType<IPrePopulationModule, PopulateGenders>("PopulateGenders", new PerHttpRequestLifetimeManager());
    container.RegisterType<IPrePopulationModule, PopulateOrigins>("PopulateOrigins", new PerHttpRequestLifetimeManager());
    container.RegisterType<IPrePopulationModule, PopulateRelationshipTypes>("PopulateRelationshipTypes", new PerHttpRequestLifetimeManager());
    container.RegisterType<IPrePopulationModule, PopulateRepresentationTypes>("PopulateRepresentationTypes", new PerHttpRequestLifetimeManager());
    container.RegisterType<IPrePopulationModule, PopulateRuleSets>("PopulateRuleSets", new PerHttpRequestLifetimeManager());
    container.RegisterType<IEnumerable<IPrePopulationModule>, IPrePopulationModule[]>();

1 个答案:

答案 0 :(得分:1)

Unity 3添加了registration by convention来处理这样的案例......

//There's other options for each parameter (and you can supply your own custom options)
container.RegisterTypes(
    AllClasses.FromLoadedAssemblies().
        Where(type => typeof(IPrePopulationModule).IsAssignableFrom(type)),
    WithMappings.FromAllInterfacesInSameAssembly,
    WithName.TypeName,
    type => new PerHttpRequestLifetimeManager());