2010-02-04 49 views
4

我們使用的代碼庫基於構造函數的依賴注入,AutoMapperUnity默認的團結類型映射。指定爲通用接口和類對

我們包裹AutoMapper通用接口...

public interface IMapper<TSource, TDestination> 
{ 
    TDestination Map(TSource source); 
} 

而實現此接口的類...

public class AutomaticMapper<TSource, TDestination> : IMapper<TSource, TDestination> 
{ 
    public TDestination Map(TSource source) 
    { 
     return AutoMapper.Mapper.Map<TSource, TDestination>(source); 
    } 
} 

這種運作良好,但它意味着,每映射我們在AutoMapper配置中定義我們需要執行額外的UnityContainer.RegisterType

這些類型映射幾乎都是形式

container.RegisterType<IMapper<ClassA, ClassB>, AutomaticMapper<ClassA, ClassB>>(); 

是沒有什麼辦法,我們可以告訴統一使用,從IMapper映射的默認類型映射到AutomaticMapper使用相同TSourceTDestination爲每他們?

回答

9

我們實際上做了幾乎相同的事情。在Unity,你可以說:

unityContainer.RegisterType(typeof(IMapper<,>), typeof(AutomaticMapper<,>)); 
1
public class AutomaticMapper : IMapper 
{ 
    public TDestination Map<TSource, TDestination>(TSource source) 
    { 
     return AutoMapper.Mapper.Map<TSource, TDestination>(source); 
    } 
}