.NET Core 中依賴注入 AutoMapper 小記

來源:互聯網
上載者:User

標籤:enc   ide   tom   pen   list   single   ext   問題   creat   

最近在 review 代碼時發現同事沒有像其他項目那樣使用 AutoMapper.Mapper.Initialize() 靜態方法配置映射,而是使用了依賴注入 IMapper 介面的方式

services.AddSingleton<IMapper>(new Mapper(new MapperConfiguration(cfg =>{    cfg.CreateMap<User, MentionUserDto>();})));

於是趁機學習瞭解一下,在 github 上發現了 AutoMapper.Extensions.Microsoft.DependencyInjection ,使用它只需通過 AutoMapper.Profile 配置映射

public class MappingProfile : Profile{    public MappingProfile()    {        CreateMap<User, MentionUserDto>();    }}

然後通過 AddAutoMapper() 進行依賴注入,它會在當前程式集自動找出所有繼承自 Profile 的子類添加到配置中

services.AddAutoMapper();

後來發現在使用 ProjectTo 時

.Take(10).ProjectTo<MentionUserDto>().ToListAsync(); 

發現如果自己使用 AddSingleton<IMapper>() ,會出現下面的錯誤(詳見博問):

Mapper not initialized. Call Initialize with appropriate configuration.

使用 AddAutoMapper() 並且將 UseStaticRegistration 為 false 時也會出現同樣的問題。

解決方案是給 ProjectTo 傳參 _mapper.ConfigurationProvider (註:傳 _mapper 不行)

.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider)

對於自己依賴注入的操作方式,後來參考  AutoMapper.Extensions.Microsoft.DependencyInjection 的實現

services.AddSingleton(config);return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));

採用了下面的方式,如果不想使用 AddAutoMapper()  通過反射自動找出 Profile ,建議使用這種方式

AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>{    cfg.AddProfile<MappingProfile>();});services.AddSingleton(config);services.AddScoped<IMapper, Mapper>();

.NET Core 中依賴注入 AutoMapper 小記

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.