Trying to add AutoMapper to Asp.net Core 2?

asp.net Mvcasp.net CoreAutomapperasp.net Core-2.0

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

If you are using AspNet Core 2.2 and AutoMapper.Extensions.Microsoft.DependencyInjection v6.1 You need to use in Startup file

services.AddAutoMapper(typeof(Startup));

Solution 2 - asp.net Mvc

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

Solution 3 - asp.net Mvc

In new version (6.1) of AutoMapper.Extensions.Microsoft.DependencyInjection nuget package you should use it as follows:

services.AddAutoMapper(Type assemblyTypeToSearch);
// OR
services.AddAutoMapper(params Type[] assemblyTypesToSearch);

e.g:

services.AddAutoMapper(typeOf(yourClass)); 

Solution 4 - asp.net Mvc

None of these worked for me, I have a .NET Core 2.2 project and the complete code for configuring the mapper looks like this(part of ConfigureService() method):

    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new SimpleMappings());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

Then I have my Mappings class which I've placed in the BL project:

public class SimpleMappings : Profile
    {
        public SimpleMappings()
        {
            CreateMap<DwUser, DwUserDto>();
            CreateMap<DwOrganization, DwOrganizationDto>();
        }
    }

And finally the usage of the mapper looks like this:

public class DwUserService : IDwUserService
    {
        private readonly IDwUserRepository _dwUserRepository;
        private readonly IMapper _mapper;

        public DwUserService(IDwUserRepository dwUserRepository, IMapper mapper)
        {
            _dwUserRepository = dwUserRepository;
            _mapper = mapper;
        }

        public async Task<DwUserDto> GetByUsernameAndOrgAsync(string username, string org)
        {
            var dwUser = await _dwUserRepository.GetByUsernameAndOrgAsync(username, org).ConfigureAwait(false);
            var dwUserDto = _mapper.Map<DwUserDto>(dwUser);

            return dwUserDto;
        }
}

Here is a similar link on the same topic: https://stackoverflow.com/questions/40275195/how-to-setup-automapper-in-asp-net-core

Solution 5 - asp.net Mvc

Install package:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 7.0.0

Nuget:
https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/

In Startup Class:

services.AddAutoMapper(typeof(Startup));

Solution 6 - asp.net Mvc

If you are using AspNet Core 2.2.Try changing your code

from:

services.AddAutoMapper();

to:

services.AddAutoMapper(typeof(Startup));

It worked for me.

Solution 7 - asp.net Mvc

I solved this by creating a class that inherits AutoMapper.Profile

    public class model_to_resource_profile : Profile
    {
        public model_to_resource_profile()
        {
            CreateMap<your_model_class, your_model_resource_class>();
        }
    }

And adding this line in the Startup.cs:

services.AddAutoMapper(typeof(model_to_resource_profile ));

Solution 8 - asp.net Mvc

In .Net 6, you can do it like

builder.Services.AddAutoMapper(typeof(Program).Assembly); // Since there is no Startup file

OR

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Basically, it requires the assembly name as shown in screenshot below enter image description here

Solution 9 - asp.net Mvc

try this, works with 2.1 and up, i have not used any previous version so can't tell.

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Solution 10 - asp.net Mvc

The official docs: https://automapper.readthedocs.io/en/latest/Dependency-injection.html#asp-net-core

> You define the configuration using profiles. And then you let > AutoMapper know in what assemblies are those profiles defined by > calling the IServiceCollection extension method AddAutoMapper at > startup:

services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

> or marker types:

services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);

Solution 11 - asp.net Mvc

Dec 6th 2019 Based upon initial attempt in a pluralsight course Building an API with ASP.NET Core by Shawn Wildermuth. As I got the error "...ambiguous 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])..."

I started researching proper syntax to implement AddAutoMapper in Core 2.2. My NuGet reference is version 7.0.0 After the tutorial had me create the Profile class in my Data repository directory which additionally referenced my model nir weiner & dev-siberia's answers above led me to trying to reference the profile class in the Startup.ConfigureServices() by name:

services.AddAutoMapper(typeof(CampProfile));

the content of the profile class is just a (no pun intended) old school map of the data class and the model in its constructor

this.CreateMap<Camp, CampModel>();  

This addressed the poor lack of documentation for this current version.

Respectfully,

ChristianProgrammer

Solution 12 - asp.net Mvc

If you are having issue with adding your auto mapper, It is better you check through the type and version you added. If it is not "AutoMapper.Extensions.Microsoft.DependencyInjection", then you won't be able to use "services.AddAutoMapper()". Sometimes, you might mistakenly add "AutoMapper

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontopcoolView Question on Stackoverflow
Solution 1 - asp.net Mvcdev-siberiaView Answer on Stackoverflow
Solution 2 - asp.net MvcTsengView Answer on Stackoverflow
Solution 3 - asp.net MvcMohammad DayyanView Answer on Stackoverflow
Solution 4 - asp.net MvcYasen RaykovView Answer on Stackoverflow
Solution 5 - asp.net MvcR M Shahidul Islam ShahedView Answer on Stackoverflow
Solution 6 - asp.net MvcAmin GolmahalleView Answer on Stackoverflow
Solution 7 - asp.net MvcCodeRedView Answer on Stackoverflow
Solution 8 - asp.net MvcShahView Answer on Stackoverflow
Solution 9 - asp.net MvcManzur AlahiView Answer on Stackoverflow
Solution 10 - asp.net MvcAskar RayapovView Answer on Stackoverflow
Solution 11 - asp.net MvcChristianProgrammerView Answer on Stackoverflow
Solution 12 - asp.net MvcAlagbe SunmboView Answer on Stackoverflow