topcool
topcool

Reputation: 2720

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?

Upvotes: 72

Views: 62306

Answers (13)

Sumith Ekanayake
Sumith Ekanayake

Reputation: 2275

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

Upvotes: 1

Shah
Shah

Reputation: 1654

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

Upvotes: 6

Alagbe Sunmbo
Alagbe Sunmbo

Reputation: 21

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

Upvotes: 2

Amin Golmahalleh
Amin Golmahalleh

Reputation: 4206

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

from:

services.AddAutoMapper();

to:

services.AddAutoMapper(typeof(Startup));

It worked for me.

Upvotes: 9

Mohammad Dayyan
Mohammad Dayyan

Reputation: 22458

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

Upvotes: 16

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

Upvotes: 10

ChristianProgrammer
ChristianProgrammer

Reputation: 305

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

Upvotes: 1

Manzur Alahi
Manzur Alahi

Reputation: 2096

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

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

Upvotes: 3

CodeRed
CodeRed

Reputation: 903

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

Upvotes: 4

Askar Rayapov
Askar Rayapov

Reputation: 168

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) /*, ...*/);

Upvotes: 2

Yasen Raykov
Yasen Raykov

Reputation: 237

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

Upvotes: 10

dev-siberia
dev-siberia

Reputation: 2865

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

Upvotes: 175

Tseng
Tseng

Reputation: 64259

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

Upvotes: 43

Related Questions