Search code examples
entity-frameworkasp.net-coreautomapperdto

AutoMapper does not work in .NET Core 8 when I use dependency injection


I am trying to use AutoMapper to map my entity with my DTO, but when I try to use dependency injection in program.cs like this:

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

I got this error:

Error CS0121
The call is ambiguous between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper(Microsoft.Extensions.DependencyInjection.IServiceCollection, params System.Type[])' and 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper(Microsoft.Extensions.DependencyInjection.IServiceCollection, params System.Type[])' EmployeeManagement.WebAPI
C:\ELM.Net\EmployeeManagement.WebAPI\Program.cs 65 Active

My DTO:

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

My Mapper conf:

public class UserRoleReMapperConfig : Profile
{
    public UserRoleReMapperConfig()
    {
        CreateMap<IdentityRole,
           UserRoleResponseDto>().ReverseMap();
        CreateMap<IdentityRole,
            createRoleRequestDto>().ReverseMap();
    }
}

Solution

  • This can be a rather annoying problem with extension methods. Especially when developers break naming rules and deviate by adding third-party namespaces into their assemblies.

    In the case of Automapper, it looks like the issue is that originally the developers separated the DI integration into a "AutoMapper.Extensions.Microsoft.DependencyInjection" package, but later integrated it into the base Automapper library. You likely have the "AutoMapper.Extensions.Microsoft.DependencyInjection" NuGet reference and can remove that package which should address your issue. The extension method is now part of the base Automapper package.

    When debugging issues like this you can identify the conflicting culprits highlighting the method in question, ("AddAutoMapper" in builder.Services.AddAutoMapper(typeof(UserRoleReMapperConfig));) right-clicking, and selecting "Go to definition". This should bring up two selections, visit each one and note which assembly they are part of. This should reveal the assemblies of the conflicting extension methods and you can investigate and try removing one of the packages.