通过阅读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(...)
功能先例指定一个特定的服务定位器