gpt4 book ai didi

c# - 非静态字段、方法或属性需要 Automapper 对象引用

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:53 25 4
gpt4 key购买 nike

我最近将我的 .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));

非静态字段、方法或属性“Mapper.Map(xxx)”需要对象引用

Automapper 在其对 Mapper 类方法的新升级中删除了 static 关键字。

最佳答案

您的问题特定于映射器的配置文件,但帖子标题也与以下问题相关。就我而言,这不是完全相同的问题,但我遇到了同样的错误。所以我想把这个分享给任何和我有同样错误的人。

看起来 Automapper 不再是静态类了。所以你需要实例化它。为此,您需要安装软件包:

安装包 AutoMapper.Extensions.Microsoft.DependencyInjection

完成后,您可以在类中注入(inject) 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);
}
}

重要的是,它可能看起来有点黑魔法,因为您从未在 ServiceCollection 中注册 IMapper。但是 Nuget 包和在您的 ConfigureServices 中调用“AddAutoMapper”会为您处理所有这一切。

PS:没有在 VS 上编写代码,但你明白了。

关于c# - 非静态字段、方法或属性需要 Automapper 对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58807216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com