1

Jimmy Bogart有一篇关于使用Automapper with an IoC container的文章。他有一个使用StructureMap的例子,但我使用的是Unity,我不确定如何正确使用一个InjectionConstructor。我如何在Unity中做到这一点?

下面是来自文章和下面的代码,这是我可怜的尝试。任何人都可以告诉我如何正确地做到这一点?

public class ConfigurationRegistry : Registry 
{ 
    public ConfigurationRegistry() 
    { 
     ForRequestedType<Configuration>() 
      .CacheBy(InstanceScope.Singleton) 
      .TheDefault.Is.OfConcreteType<Configuration>() 
      .CtorDependency<IEnumerable<IObjectMapper>>().Is(expr => expr.ConstructedBy(MapperRegistry.AllMappers)); 

     ForRequestedType<IConfigurationProvider>() 
      .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<Configuration>()); 

     ForRequestedType<IConfiguration>() 
      .TheDefault.Is.ConstructedBy(ctx => ctx.GetInstance<Configuration>()); 
    } 
} 

我尝试:

container.RegisterType<IConfiguration, Configuration>(new SingletonLifetime()) 
        .Configure<InjectedMembers>() 
         .ConfigureInjectionFor<Configuration>(
          new InjectionConstructor(typeof(IEnumerable<IObjectMapper>)), MapperRegistry.AllMappers); 

回答

1

这是我落得这样做:

 IEnumerable<IObjectMapper> allMappers = new List<IObjectMapper>() { 
      new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers()), 
      new StringMapper(), 
      new FlagsEnumMapper(), 
      new EnumMapper(), 
      new ArrayMapper(), 
      new DictionaryMapper(), 
      new EnumerableMapper(), 
      new AssignableMapper(), 
      //new TypeConverterMapper(), 
      new NullableMapper(), 
     }; 

     container.RegisterType<Configuration>(new SingletonLifetime()) 
         .Configure<InjectedMembers>() 
          .ConfigureInjectionFor<Configuration>(
           new InjectionConstructor(allMappers)); 

    container.RegisterType<IConfigurationProvider, Configuration>(); 
    container.RegisterType<IConfiguration, Configuration>(); 
    container.RegisterType<IMappingEngine, MappingEngine>(); 

这工作,但如果别人有更好的实现我所有的耳朵和这仍然有一个赏金。

+0

使用Automapper MapperRegistry.AllMappers()静态方法获取所有映射器而非手动。但是是我在SM中使用的类似设置,除了冷凝第一条语句 – 2009-08-01 16:41:17