我有一组我想用 Automapper 映射到的类。但是,每个类都有一个构造函数参数。此参数对于所有成员都是同一类型,但在我要进行映射之前我不知道要提供的值。
我找到了 ConstructUsing
方法,但这需要我在配置时指定参数值。我更愿意在映射时执行此操作,以避免需要为参数的每个实例创建单独的 MappingEngine
。我找到了映射到已创建目标对象的 Map
重载。这很有用,但不适用于列表或对象图。
本质上,我正在寻找类似 Autofac 的 resolve 方法的东西,它只适用于 Automapper 的 Map
方法。
Resolve<IFoo>( new TypedParameter( typeof( IService ), m_service) );
最佳答案
通过阅读 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(...)
的函数
关于c# - 在映射时向 Automapper 提供构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446599/