Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 904
abbs Avatar asked Nov 11 '19 19:11

abbs


People also ask

Why do we need AutoMapper in C#?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What is the use of AutoMapper in MVC?

AutoMapper is an external component that helps in creating a mapping between a source and destination model types. Once the mapping is created then the source model object can be converted to a destination model object with ease and with less cluttered code.


1 Answers

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.

like image 185
curiousBoy Avatar answered Sep 20 '22 21:09

curiousBoy