2012-11-19 56 views
1

我有一组我想用Automapper映射到的类。但是,每个类都有一个构造函数参数。这个参数对于所有成员来说都是相同的类型,但是我不知道要提供的值,直到我想要做我的映射。在映射时向Automapper提供构造函数参数

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

本质上,我正在寻找类似Autofac的解析方法,只适用于Automapper的Map方法。

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

回答

4

通过阅读Automapper源代码,我发现了一个可行的解决方案,我将在下面介绍。

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

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

然后调用地图时,您可以使用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表示上述接管提供给IConfiguration.ConstructServicesUsing(...)

功能先例指定一个特定的服务定位器
相关问题