71

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?

SanS
  • 385
  • 8
  • 21
topcool
  • 2,498
  • 7
  • 28
  • 52
  • Don't mix Versions of .NET Core. You probably have references to some 1.1 assemblies of .NET Core or ASP.NET Core. YOu have to update **ALL** of them to the same version (i.e. 2.0 or 2.1-rc) or you are still referencing an outdated Automapper version – Tseng May 18 '18 at 12:28

12 Answers12

173

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));
dev-siberia
  • 2,746
  • 2
  • 21
  • 17
  • 12
    FYI for the next one that bumps into this: I had to install Microsoft.Extensions.DependencyInjection.Abstractions to make services.AddAutoMapper(typeof(Startup)); work – Marius May 22 '19 at 05:08
  • 3
    on .net core 2.2,this eliminated the build error for me, but still failed at runtime for lack of mapping configurations.. what worked for me was to list all of my profile classes inside the statement. i.e: services.AddAutoMapper(typeof(profileClassName1),typeof(profileClassName2)); – nir weiner Aug 29 '19 at 08:00
  • 2
    @nirweiner's comment is correct, but you only have to point to one of the profile classes, because it is asking for an assembly to search in. dev-siberia's answer works if your profile configurations are in the same assembly. – CularBytes Sep 22 '19 at 14:48
43

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

Tseng
  • 61,549
  • 15
  • 193
  • 205
16

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)); 
Mohammad Dayyan
  • 21,578
  • 41
  • 164
  • 232
  • What do you mean by assemblyType? I have tons of profile which is why i can't afford adding them one by one. Sorry new in C# here. Thanks! – sshanzel Jan 16 '20 at 10:21
  • Something like `services.AddAutoMapper(typeOf(yourClass)); ` – Mohammad Dayyan Jan 16 '20 at 18:23
  • Yeah, i mean those answers are mentioned above and it truly works but i was just wondering what could be the explanation of what assemblyType. Sorry i'm really a noob one – sshanzel Jan 16 '20 at 18:46
  • I mean one or multi types in an assembly. if you wanna find, what is an assembly https://stackoverflow.com/questions/1362242/what-exactly-is-an-assembly-in-c-sharp-or-net – Mohammad Dayyan Jan 16 '20 at 19:49
10

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));
9

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: How to setup Automapper in ASP.NET Core

Yasen Raykov
  • 198
  • 1
  • 2
  • 7
9

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

from:

services.AddAutoMapper();

to:

services.AddAutoMapper(typeof(Startup));

It worked for me.

Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
6

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

Shah
  • 1,604
  • 4
  • 20
  • 33
4

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 ));
CodeRed
  • 905
  • 1
  • 6
  • 24
3

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

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

Manzur Alahi
  • 1,870
  • 23
  • 19
1

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) /*, ...*/);
Askar Rayapov
  • 139
  • 1
  • 7
1

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

Ramil Aliyev 007
  • 4,437
  • 2
  • 31
  • 47
0

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