.NET Core 中依赖注入 AutoMapper 小记

最近在 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>();
相关文章
相关标签/搜索