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