asp.net-mvcasp.net-coreautomapperasp.net-core-2.0

Trying to add AutoMapper to Asp.net Core 2?


I worked on a asp.net core 1.1 project a while ago and use in projetc AutoMapper.

in asp.net core 1.1, I add services.AddAutoMapper() in startup file :

StartUp file in asp.net core 1.1:

    public void ConfigureServices(IServiceCollection services)
    {
        //Some Code

        services.AddMvc();
        services.AddAutoMapper();
    }

And I use AutoMapper in Controller easily.

Controller :

 public async Task<IActionResult> AddEditBook(AddEditBookViewModel model)
 {
    Book bookmodel = AutoMapper.Mapper.Map<AddEditBookViewModel, Book>(model);
    context.books.Add(bookmodel);
    context.SaveChanges();
 }

And everything was fine. But I'm currently working on a Asp.net Core 2 project and I get the error with services.AddAutoMapper() in sturtap file.

Error CS0121 The call is ambiguous between the following methods or properties: 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])' and 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])'

What is the reason for this error? Also, services.AddAutoMapper in asp.net core 2 has some parameters. what should I send to this parameter?


Solution

  • You likely updated your ASP.NET Core dependencies, but still using outdated AutoMapper.Extensions.Microsoft.DependencyInjection package.

    For ASP.NET Core you need at least Version 3.0.1 from https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/3.0.1

    Which references AutoMapper 6.1.1 or higher.

    AutoMapper (>= 6.1.1)

    Microsoft.Extensions.DependencyInjection.Abstractions (>= 2.0.0)

    Microsoft.Extensions.DependencyModel (>= 2.0.0)

    The older packages depend on Microsoft.Extensions.DependencyInjection.Abstractions 1.1.0 and can't be used with ASP.NET Core since there have been breaking changes between Microsoft.Extensions.DependencyInjection.Abstractions 1.1.0 and 2.0