2016-02-22 61 views
1

我需要將域對象映射到我的SPA中的DTO對象,該對象基於Angular和WebAPI構建。對於此功能,我決定使用一些自動映射工具。在我的映射過程中,我需要提供一些可以擴展全局映射設置的上下文信息。其實我是想實現這個:內聯映射設置

int i = 10; 
var mapper = config.CreateMapper(); 
mapper.Map<Source, Dest>(src, opt => { 
    opt.BeforeMap((src, dest) => src.Value = src.Value + i); 
    opt.AfterMap((src, dest) => dest.Name = HttpContext.Current.Identity.Name); 
}); 

這是Automapper代碼。但我不想使用Atomapper,因爲它非常慢。

我已經看過其他工具,如(Mapster,ExpressMapper)。這些工具很酷且很快,但據我所知,它們不支持內聯設置。

有人可以告訴我一些其他automapping工具,它支持此功能。或者,也許有人向我諮詢,如何用上述工具之一來實現?

+1

AutoMapper速度慢的原因是因爲您現在突出顯示的確切功能。這些功能非常昂貴,並且讓速度變慢。 –

回答

0

ValueInjecter可以創建自定義地圖:

Mapper.AddMap<Customer, CustomerInput>(src => 
{ 
    var res = new CustomerInput(); 
    res.InjectFrom(src); // maps properties with same name and type 
    res.FullName = src.FirstName + " " + src.LastName; 
    return res; 
}); 

EmitMapper有​​方法:

var mapper = ObjectMapperManager 
    .DefaultInstance 
    .GetMapper<Source, Destination>(
     new DefaultMapConfig() 
     .PostProcess<Destination>((destination, state) => { destination.list.Sort(); return destination;}) 
    ); 

如果AutoMapper是你太慢了,然後EmitMapper適應,也許是不錯的選擇。看看這個基準:Emit mapper vs valueinjecter or automapper performance

不幸的是EmitMapper幾年前就放棄了。

+0

謝謝。這是真正的麻煩。也許你知道用手寫映射實現這一點的一些技巧?我的意思是自動映射對象的一部分,並由我自己映射其餘部分。你能提出一些方便的方法來做到這一點: – Stalso

+0

@Stalso,你可以使用'FastMapper'作爲自動映射部分。或者類似的工具比AutoMapper快得多,而且仍然活着。然後留下另一部分手寫並編寫一個用於組合這兩部分的包裝器,如'MyMapper.Map(source,dest)'。很抱歉,如果這是一個明顯的建議。 –

+0

是的,很明顯。)然而,謝謝。我已經用Mapster實現了一些技術,我將在測試之後發佈它。 – Stalso