1

I get error when usinng AutoMaper for netcore 2.1 projet

Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance. AutoMapper.Mapper.get_Configuration() in Mapper.cs, line 23

I had configed it

 public class AutoMapperConfig
{
    public static MapperConfiguration RegisterMappings()
    {
        return new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new DomainToViewModelMappingProfile());
            cfg.AddProfile(new ViewModelToDomainMappingProfile());
        });
    }
}

File DomainToViewModelMappingProfile.cs

public class DomainToViewModelMappingProfile : Profile{
      public DomainToViewModelMappingProfile(){
             CreateMap<Function, FunctionViewModel>();
             CreateMap<AppUser, AppUserViewModel>();
             CreateMap<AppRole, AppRoleViewModel>();
 }
}

File Startup.cs

 services.AddSingleton(Mapper.Configuration);
        services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<AutoMapper.IConfigurationProvider>(), sp.GetService));

Anyone can help me? Thanks you!

hiimdat95
  • 125
  • 3
  • 10

3 Answers3

6

I would suggest you to use the automapper extension for microsoft-ioc.

In your configureservice-method (startup-class):

services.AddAutoMapper(typeof(Startup).Assembly);

You don't need to configure the profiles manually then, because the extension will scan for the types in the given assembly or assemblies you pass to it.

alsami
  • 8,996
  • 3
  • 25
  • 36
2

Are you using .ProjectTo<>() in any of the calls that you are doing? If yes, try to add the configuration in the parameters:

IMapper _mapper; //Inject in constructor

_repository.GetAll().ProjectTo<YourProjection>(_mapper.ConfigurationProvider);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
g_brahimaj
  • 197
  • 7
  • 21
-1

This worked for me.

Solution

In Startup.cs, you can fix it by replacing

services.AddSingleton(Mapper.Configuration);

with

services.AddSingleton<IConfigurationProvider>(AutoMapperConfig.RegisterMappings());

Source

Community
  • 1
  • 1
Wictor Chaves
  • 957
  • 1
  • 13
  • 21