Mapper not initialized. Call Initialize with appropriate configuration [duplicate]

核能气质少年 提交于 2019-12-08 06:13:29

问题


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!


回答1:


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.




回答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);



回答3:


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



来源:https://stackoverflow.com/questions/51625446/mapper-not-initialized-call-initialize-with-appropriate-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!