最近在 review 代碼時發現同事沒有像其餘項目那樣使用 AutoMapper.Mapper.Initialize() 靜態方法配置映射,而是使用了依賴注入 IMapper 接口的方式git
services.AddSingleton<IMapper>(new Mapper(new MapperConfiguration(cfg => { cfg.CreateMap<User, MentionUserDto>(); })));
因而趁機學習瞭解一下,在 github 上發現了 AutoMapper.Extensions.Microsoft.DependencyInjection ,使用它只需經過 AutoMapper.Profile 配置映射github
public class MappingProfile : Profile { public MappingProfile() { CreateMap<User, MentionUserDto>(); } }
而後經過 AddAutoMapper() 進行依賴注入,它會在當前程序集自動找出全部繼承自 Profile 的子類添加到配置中app
services.AddAutoMapper();
後來發如今使用 ProjectTo 時ide
.Take(10) .ProjectTo<MentionUserDto>() .ToListAsync();
發現若是本身使用 AddSingleton<IMapper>() ,會出現下面的錯誤(詳見博問):學習
Mapper not initialized. Call Initialize with appropriate configuration.
使用 AddAutoMapper() 而且將 UseStaticRegistration 爲 false 時也會出現一樣的問題。ui
解決方法是給 ProjectTo 傳參 _mapper.ConfigurationProvider (注:傳 _mapper 不行)spa
.ProjectTo<MentionUserDto>(_mapper.ConfigurationProvider)
對於本身依賴注入的操做方式,後來參考 AutoMapper.Extensions.Microsoft.DependencyInjection 的實現code
services.AddSingleton(config); return services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
採用了下面的方式,若是不想使用 AddAutoMapper() 經過反射自動找出 Profile ,建議使用這種方式blog
AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg => { cfg.AddProfile<MappingProfile>(); }); services.AddSingleton(config); services.AddScoped<IMapper, Mapper>();