18

I recently Upgraded my .net core to 3.0 and Automapper from 6.2 to 9.0. Now the automapper is throwing the following compile time error when using mapper.map inside mapfrom function.

CreateMap<DomainEntity, destination>()
            .ForMember(dest => dest.userId, opt => opt.MapFrom(src => Mapper.Map<.UserInfo, string>(src.UserDetails)))
            .ForMember(dest => dest.alertKey, opt => opt.MapFrom(src => src.Key));

An object reference is required for the non-static field, method, or property 'Mapper.Map(xxx)'

Automapper has removed static keyword in its new upgrade for Mapper class Methods.

Progman
  • 16,827
  • 6
  • 33
  • 48
abbs
  • 226
  • 2
  • 3
  • 12

2 Answers2

16

Your question was specific to profile of the mapper but the post title ties with the below issue too. In my case, it was not exact same problem but I was getting same error. So I wanted to share this for anyone who had same error like mine.

Looks like Automapper is not a static class anymore. So you will need to instantiate it. To be able to do that, you will need to install the package :

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

Once it is done, than you can inject IMapper instance in your class like:

public MyClass {

     private readonly IMapper _mapper;

     public MyClass(IMapper mapper){
          _mapper = mapper;
     }

     public DtoType SomeMethod(EntityType entity){
          // do your mapping..
          var myDtoType = _mapper.Map<DtoType>(entity);
     }
}

Important part is, it may look like a bit of black magic since you never registered IMapper in the ServiceCollection. But the Nuget package and the call to “AddAutoMapper” in your ConfigureServices takes care of all of this for you.

PS: didn't write the code on VS but you got the idea.

curiousBoy
  • 6,334
  • 5
  • 48
  • 56
3

I also encounter the problem recently, here is what I did

Installed this package AutoMapper.Extensions.Microsoft.DependencyInjection. This package is a dependency on AutoMapper. It also contains ASP.NET core specific extensions for AutoMapper allowing it to play nice with the built-in dependency injection system.

Then follow the steps on the link below. Then you should be good to go

https://dotnetcoretutorials.com/2017/09/23/using-automapper-asp-net-core/

Onuchukwu Chika
  • 249
  • 1
  • 2
  • 7