Trying to add AutoMapper to Asp.net Core 2?
Asked Answered
G

13

72

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?

Grof answered 18/5, 2018 at 12:17 Comment(1)
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 versionCelebration
C
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

Celebration answered 18/5, 2018 at 12:36 Comment(3)
Thanks. i updated AutoMapper.Extensions.Microsoft.DependencyInjection and error solved.Grof
do in console dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 8.0.1Hasan
For dotnet 5.0, AutoMapper.Extensions.Microsoft.DependencyInjection 8.1.1 doesn't seem to work.Boggess
P
175

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));
Para answered 6/5, 2019 at 9:26 Comment(3)
FYI for the next one that bumps into this: I had to install Microsoft.Extensions.DependencyInjection.Abstractions to make services.AddAutoMapper(typeof(Startup)); workShorthand
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));Wang
@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.Danita
C
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

Celebration answered 18/5, 2018 at 12:36 Comment(3)
Thanks. i updated AutoMapper.Extensions.Microsoft.DependencyInjection and error solved.Grof
do in console dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 8.0.1Hasan
For dotnet 5.0, AutoMapper.Extensions.Microsoft.DependencyInjection 8.1.1 doesn't seem to work.Boggess
B
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)); 
Butterwort answered 6/5, 2019 at 5:15 Comment(4)
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!Rotten
Something like services.AddAutoMapper(typeOf(yourClass)); Butterwort
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 oneRotten
I mean one or multi types in an assembly. if you wanna find, what is an assembly #1362742Butterwort
D
10

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

Dropout answered 16/6, 2019 at 8:24 Comment(2)
Thanks so much for posting this complete example!Power
This is the only example that worked for me. Thanks!Bunyan
F
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));
Footer answered 9/5, 2020 at 15:17 Comment(0)
A
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.

Adelaideadelaja answered 22/12, 2019 at 8:14 Comment(0)
C
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

Cubature answered 23/1, 2022 at 16:44 Comment(0)
S
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 ));
Sourdough answered 11/9, 2019 at 7:56 Comment(0)
F
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());

Factitious answered 10/10, 2019 at 18:41 Comment(1)
This answer is works for me when doing AutoMapper for additional project on my solution. Thank bro.Rolland
W
2

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

Waldheim answered 24/12, 2021 at 6:34 Comment(0)
I
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) /*, ...*/);
Interlocutor answered 7/9, 2019 at 7:0 Comment(0)
L
1

I also face same issue with .NET 8

It resolved by updating AutoMapper and AutoMapper.Extensions.Microsoft.DependencyInjection to same version

enter image description here

// Add services to the container.
builder.Services.AddAutoMapper(typeof(MappingConfig));
Linstock answered 12/2 at 14:19 Comment(1)
I had the same issue, this resolved it for me. I'm also using AutoMapper.Collection.EntityFrameworkCore on version 10.0.0 and had to bring it back to 9.0.0. Have to wait for AutoMapper.Extensions.Microsoft.DependencyInjection to hit version 13.0.1Greasy
S
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

Spoony answered 6/12, 2019 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.