2012-11-19 55 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(...)

功能先例指定一個特定的服務定位器
相關問題