3

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

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

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

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

1 回答 1

8

通过阅读 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 );

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

于 2012-11-19T15:32:19.610 回答