本文主要介紹了關(guān)于.NET Core中依賴注入AutoMapper的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹:
最近在 review 代碼時發(fā)現(xiàn)同事沒有像其他項(xiàng)目那樣使用 AutoMapper.Mapper.Initialize()
靜態(tài)方法配置映射,而是使用了依賴注入 IMapper 接口的方式
1
2
3
4
|
services.AddSingleton<IMapper>( new Mapper( new MapperConfiguration(cfg => { cfg.CreateMap<User, MentionUserDto>(); }))); |
于是趁機(jī)學(xué)習(xí)了解一下,在 github 上發(fā)現(xiàn)了 AutoMapper.Extensions.Microsoft.DependencyInjection ,使用它只需通過 AutoMapper.Profile
配置映射
1
2
3
4
5
6
7
|
public class MappingProfile : Profile { public MappingProfile() { CreateMap<User, MentionUserDto>(); } } |
然后通過 AddAutoMapper()
進(jìn)行依賴注入,它會在當(dāng)前程序集自動找出所有繼承自 Profile 的子類添加到配置中
1
|
services.AddAutoMapper(); |
后來發(fā)現(xiàn)在使用 ProjectTo 時
1
2
3
|
.Take(10) .ProjectTo<MentionUserDto>() .ToListAsync(); |
發(fā)現(xiàn)如果自己使用 AddSingleton<IMapper>()
,會出現(xiàn)下面的錯誤(詳見博問):
1
|
Mapper not initialized. Call Initialize with appropriate configuration. |
使用 AddAutoMapper()
并且將 UseStaticRegistration 為 false 時也會出現(xiàn)同樣的問題。
解決方法是給 ProjectTo 傳參 _mapper.ConfigurationProvider
(注:傳 _mapper 不行)
1
|
.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider) |
對于自己依賴注入的操作方式,后來參考 AutoMapper.Extensions.Microsoft.DependencyInjection
的實(shí)現(xiàn)
1
2
|
services.AddSingleton(config); return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService)); |
采用了下面的方式,如果不想使用 AddAutoMapper()
通過反射自動找出 Profile ,建議使用這種方式
1
2
3
4
5
6
|
AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg => { cfg.AddProfile<MappingProfile>(); }); services.AddSingleton(config); services.AddScoped<IMapper, Mapper>(); |
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:http://www.cnblogs.com/dudu/p/8279114.html