2017-08-11 77 views
-1

我使用AutoMapper的ASP.net核心。爲了讓DI運行,我用的是AutoMapper.Extensions.Microsoft.DependencyInjection的NuGet封裝,讓AutoMapper通過通過Asp.Net核心添加AutoMapper核心依賴注入並注入配置文件

private static void InitializeAutoMapper(IServiceCollection services) 
    { 
     services.AddAutoMapper(); 
    } 

這正常註冊的配置文件,但是對於一些配置文件,我想也注入一些依賴於它們,例如:

public class IndividualDtoProfile : Profile 
{ 
    private readonly IIndividualFactory _individualFactory; 
    private readonly IMapper _mapper; 

    public IndividualDtoProfile(IIndividualFactory individualFactory, IMapper mapper) 
    { 
     _individualFactory = individualFactory; 
     _mapper = mapper; 
    } 

    public IndividualDtoProfile() 
    { 
     CreateMap<Individual, IndividualDto>(); 

     CreateMap<IndividualDto, Individual>() 
      .ConstructUsing(
       dto => 
       { 
        var gender = _mapper.Map<IndividualGender>(dto.Gender); 
        return _individualFactory.CreateIndividual(dto.FirstName, dto.LastName, gender, dto.BirthDate); 
       }); 
    } 
} 

唯一相關的討論,我發現在這裏:https://groups.google.com/forum/#!topic/automapper-users/5XK7pqGu_Tg

還幾乎似乎暗示不使用的現有可能性善良,但手動映射簡介秒。我唯一能看到的另一種可能是提供一個靜態的ServiceProvider-Singleton,這看起來不太吸引人。

是否有可能將Auto.Net與ASP.Net Core一起使用,並讓依賴注入到Profiles中?

編輯:由於評論,可能我也是一些根本錯誤:我正在學習域驅動設計,我有一個應用程序層。我想將從Web服務中使用的DTO映射回域實體,並且我認爲,在那裏使用工廠也是有意義的,否則我會繞過工廠中的邏輯。

+0

在這裏添加DI真的有意義嗎?最後,它只是將一個對象映射到另一個對象。如果你有測試,你也需要測試/模擬映射。從我的角度來看,雙重工作。 – Artiom

+0

hm?我不明白你的觀點:我想用AutoMapper進行一般映射,但對於某些地圖,我希望使用工廠以保證一些不變量並確保每個對象都是爲其特定工廠創建的。 –

+0

爲什麼你要在配置文件中使用/注入'IMapper'?配置文件用於在映射器準備使用之前添加註冊(即通過Mapper.AssertConfigurationIsValid()執行驗證)。雖然我通常更喜歡在任何地方注入IMapper,但是有一些限制。你在使用Automapper的EF預測嗎?由於'.ProjectTo()'方法使用靜態的'Mapper'類代替 – Tseng

回答

1

這是不支持開箱即用的設計。如果你想要它,你必須使用你的DI容器自己做。這已經被討論過很多次了。例如,here。該docs

+0

謝謝,然後尋找另一個solutuon。 –

相關問題