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