C# – Automapper Object reference is required for the non static field, method or property

.net-core-3.0automapper-9c

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.

Best Answer

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.