abb*_*bbs 12 c# .net-core-3.0 automapper-9
我最近将我的 .net 核心升级到 3.0,并将 Automapper 从 6.2 升级到 9.0。现在,在 mapfrom 函数中使用 mapper.map 时,automapper 会抛出以下编译时错误。
CreateMap<DomainEntity, destination>()
.ForMember(dest => dest.userId, opt => opt.MapFrom(src => Mapper.Map<.UserInfo, string>(src.UserDetails)))
.ForMember(dest => dest.alertKey, opt => opt.MapFrom(src => src.Key));
Run Code Online (Sandbox Code Playgroud)
非静态字段、方法或属性“Mapper.Map(xxx)”需要对象引用
Automapper 在 Mapper 类方法的新升级中删除了 static 关键字。
cur*_*Boy 10
您的问题特定于映射器的个人资料,但帖子标题也与以下问题有关。就我而言,这不是完全相同的问题,但我遇到了同样的错误。所以我想把这个分享给和我一样有同样错误的人。
看起来 Automapper 不再是静态类了。所以你需要实例化它。为了能够做到这一点,您需要安装软件包:
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
完成后,您可以在类中注入 IMapper 实例,例如:
public MyClass {
private readonly IMapper _mapper;
public MyClass(IMapper mapper){
_mapper = mapper;
}
public DtoType SomeMethod(EntityType entity){
// do your mapping..
var myDtoType = _mapper.Map<DtoType>(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
重要的部分是,它可能看起来有点像黑魔法,因为您从未在 ServiceCollection 中注册 IMapper。但是 Nuget 包和 ConfigureServices 中对“AddAutoMapper”的调用会为您处理所有这些。
PS:没有在VS上写代码,但你有想法。
我最近也遇到这个问题,我是这样做的
安装了这个包AutoMapper.Extensions.Microsoft.DependencyInjection。该包依赖于 AutoMapper。它还包含针对 AutoMapper 的 ASP.NET 核心特定扩展,使其能够与内置依赖项注入系统很好地配合。
然后按照下面链接中的步骤进行操作。那么你应该可以走了
https://dotnetcoretutorials.com/2017/09/23/using-automapper-asp-net-core/