在Mapping时向Automapper提供构造函数参数

时间:2012-11-19 01:37:29

标签: c# dependency-injection automapper

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

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

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

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

1 个答案:

答案 0 :(得分:5)

通过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(...)的功能

相关问题