亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

.NET Core中依賴注入AutoMapper的方法示例

 更新時(shí)間:2018年01月14日 09:49:54   作者:dudu  
這篇文章主要給大家介紹了關(guān)于.NET Core中依賴注入AutoMapper的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

本文主要介紹了關(guān)于.NET Core中依賴注入AutoMapper的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹:

最近在 review 代碼時(shí)發(fā)現(xiàn)同事沒有像其他項(xiàng)目那樣使用 AutoMapper.Mapper.Initialize() 靜態(tài)方法配置映射,而是使用了依賴注入 IMapper 接口的方式

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 配置映射

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

然后通過 AddAutoMapper() 進(jìn)行依賴注入,它會(huì)在當(dāng)前程序集自動(dòng)找出所有繼承自 Profile 的子類添加到配置中

services.AddAutoMapper();

后來發(fā)現(xiàn)在使用 ProjectTo 時(shí)

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

發(fā)現(xiàn)如果自己使用 AddSingleton<IMapper>() ,會(huì)出現(xiàn)下面的錯(cuò)誤(詳見博問):

Mapper not initialized. Call Initialize with appropriate configuration.

使用 AddAutoMapper() 并且將 UseStaticRegistration 為 false 時(shí)也會(huì)出現(xiàn)同樣的問題。

解決方法是給 ProjectTo 傳參 _mapper.ConfigurationProvider 注:傳 _mapper 不行)

.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider)

對(duì)于自己依賴注入的操作方式,后來參考  AutoMapper.Extensions.Microsoft.DependencyInjection 的實(shí)現(xiàn)

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

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

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

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論