通過閱讀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(...)
功能先例指定一個特定的服務定位器