温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在.NET Core中注入AutoMapper依赖

发布时间:2021-04-08 17:36:59 来源:亿速云 阅读:430 作者:Leah 栏目:开发技术

怎么在.NET Core中注入AutoMapper依赖?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

最近在 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>();

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI