映射器未初始化.用适当的配置呼叫初始化 [英] Mapper not initialized. Call Initialize with appropriate configuration

查看:371
本文介绍了映射器未初始化.用适当的配置呼叫初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将AutoMaper用于netcore 2.1 projet时出现错误

I get error when usinng AutoMaper for netcore 2.1 projet

映射器未初始化.调用具有适当配置的初始化.如果您尝试通过容器或其他方式使用Mapper实例,请确保您没有对静态Mapper.Map方法的任何调用,如果您使用ProjectTo或UseAsDataSource扩展方法,请确保,请确保您传入适当的IConfigurationProvider实例. Mapper.cs中的 AutoMapper.Mapper.get_Configuration(),第23行

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

我已经配置了

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

文件DomainToViewModelMappingProfile.cs

File DomainToViewModelMappingProfile.cs

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

File Startup.cs

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!

推荐答案

我建议您使用 automapper扩展(适用于microsoft-ioc).

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

在您的configureservice方法(启动类)中:

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.

这篇关于映射器未初始化.用适当的配置呼叫初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆