【问题标题】:How do I do this in Unity?如何在 Unity 中执行此操作?
【发布时间】:2009-07-24 21:49:19
【问题描述】:

Jimmy Bogart 有一篇关于使用 Automapper with an IoC container 的文章。他有一个使用 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);

【问题讨论】:

    标签: inversion-of-control structuremap unity-container automapper


    【解决方案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>();
    

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

    【讨论】:

    • 使用 Automapper MapperRegistry.AllMappers() 静态方法获取所有映射器,而不是手动获取。但是是的,我在 SM 中使用了类似的设置,除了压缩第一条语句
    • 这就是我的问题的一部分。 Configuration 的构造函数采用 IEnumerable 但 MapperRegistry.AllMappers() 静态方法返回 Func>
    • 那么你会做TypeMapObjectMapperRegistry.AllMappers()()。关键是第二组括号。它会调用从AllMappers 返回的委托并返回IEnumerable&lt;IObjectMapper&gt; :)
    • 另外... 什么是 SingletonLifetime,您为什么选择编写它,而不是使用 ContainerControlledLifetimeManager?只是好奇。
    • 这只是一个包装。对我和我的团队来说,它读起来更好:)
    猜你喜欢
    • 2010-10-03
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多