当我使用依赖注入时,AutoMapper 在 .NET Core 8 中不起作用

问题描述 投票:0回答:1

我正在尝试使用 AutoMapper 将我的实体与 DTO 进行映射,但是当我尝试在

program.cs
中使用依赖项注入时,如下所示:

builder.Services.AddAutoMapper(typeof(UserRoleReMapperConfig));

我收到此错误:

错误CS0121
以下方法或属性之间的调用不明确:“Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper(Microsoft.Extensions.DependencyInjection.IServiceCollection, params System.Type[])”和“Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper( Microsoft.Extensions.DependencyInjection.IServiceCollection,参数 System.Type[])' EmployeeManagement.WebAPI
C:\ELM.Net\EmployeeManagement.WebAPI\Program.cs 65 活动

我的DTO:

public class UserRoleResponseDto
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string NormalizedName { get; set; }
    public string ConcurrencyStamp { get; set; }
}

我的映射器配置:

public class UserRoleReMapperConfig : Profile
{
    public UserRoleReMapperConfig()
    {
        CreateMap<IdentityRole,
           UserRoleResponseDto>().ReverseMap();
        CreateMap<IdentityRole,
            createRoleRequestDto>().ReverseMap();
    }
}
entity-framework asp.net-core automapper dto
1个回答
0
投票

对于扩展方法来说,这可能是一个相当烦人的问题。特别是当开发人员违反命名规则并通过向程序集中添加第三方命名空间来偏离时。

就 Automapper 而言,问题似乎在于最初开发人员将 DI 集成分离到“AutoMapper.Extensions.Microsoft.DependencyInjection”包中,但后来将其集成到基础 Automapper 库中。您可能拥有“AutoMapper.Extensions.Microsoft.DependencyInjection”NuGet 参考,并且可以删除该包来解决您的问题。

为什么他们选择使用命名空间“Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper”而不是“AutoMapper.Extensions.Microsoft.DependencyInjection.AddAutoMapper”?

在调试此类问题时,您可以识别冲突的罪魁祸首 突出显示有问题的方法,(

builder.Services.AddAutoMapper(typeof(UserRoleReMapperConfig));
中的“AddAutoMapper”)右键单击,然后选择“转到定义”。这应该会出现两个选择,访问每个选项并记下它们属于哪个程序集。这应该会显示冲突的扩展方法的程序集,您可以调查并尝试删除其中一个包。

© www.soinside.com 2019 - 2024. All rights reserved.