【问题标题】:Provide constructor parameter to Automapper at time of Mapping在映射时向 Automapper 提供构造函数参数
【发布时间】:2012-11-19 01:37:28
【问题描述】:

我想用 Automapper 映射到一组类。但是,每个类都有一个构造函数参数。对于所有成员,此参数的类型相同,但直到我想要进行映射时,我才知道要提供的值。

我找到了ConstructUsing 方法,但这需要我在配置时指定参数值。我宁愿在映射时执行此操作,以避免需要为参数的每个实例创建单独的 MappingEngine。我发现了映射到已经创建的目标对象的Map 重载。这很有帮助,但不适用于列表或对象图。

基本上,我正在从 Autofac 寻找类似这种解决方法的东西,仅适用于 Automapper 的 Map 方法。

Resolve<IFoo>( new TypedParameter( typeof( IService ), m_service) );

【问题讨论】:

    标签: c# dependency-injection automapper


    【解决方案1】:

    通读 Automapper 源代码,我找到了一个可行的解决方案,如下所述。

    首先,您需要指定要使用服务定位器进行构造。

    IConfiguration configuration = ...;
    configuration.CreateMap<Data.Entity.Address, Address>().ConstructUsingServiceLocator();
    

    然后在调用map时,使用opts参数指定具体的服务定位器

    // Use DI container or manually construct function
    // that provides construction using the parameter value specified in question.
    // 
    // This implementation is somewhat Primitive, 
    // but will work if parameter specified is always the only parameter
    Func<Type, object> constructingFunction =
        type => return Activator.CreateInstance( type, new object[] { s_service } );
    
    mappingEngine.Map<Data.Entity.Address, Address>(
        source, opts: options => options.ConstructServicesUsing( constructingFunction );
    

    上面constructingFunction指示的“ServiceLocator”优先于IConfiguration.ConstructServicesUsing(...)提供的功能

    【讨论】:

    • 如果 Adam 还和我们在一起,我相信他会给你很多关于任何其他方式的细节。不幸的是,他于七月去世。我是他的父亲,刚刚获得了此帐户的访问权限,自从您今天发表评论后,我想我会与您联系。
    • 非常抱歉您的损失。看起来是个聪明人。愿他安息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2011-12-29
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多