Trying to add AutoMapper to Asp.net Core 2?

Solution 1:

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:

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:

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:

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