1

Jimmy Bogart 有一篇关于将Automapper 与 IoC 容器一起使用的文章。他有一个使用 StructureMap 的示例,但我使用的是 Unity,我不确定如何正确使用 InjectionConstructor。

以下是文章中的代码,下面是我的糟糕尝试。谁能告诉我如何正确地做到这一点?

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);
4

1 回答 1

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>();

这行得通,但如果其他人有更好的实现,我会全神贯注,这仍然有赏金。

于 2009-07-30T00:40:11.503 回答