自动映射器错误,指出未初始化映射器 [英] Automapper error saying mapper not initialized

查看:205
本文介绍了自动映射器错误,指出未初始化映射器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Automapper 5.2.我已将链接用作基础.我将分步描述我所经历的设置Automapper的过程.

I am using Automapper 5.2. I have used as a basis this link. I will describe, in steps, the process of setting up Automapper that I went through.

首先,我如图所示将Automapper添加到Project.json:

First I added Automapper to Project.json as indicated:

PM> Install-Package AutoMapper

第二我创建了一个文件夹,用于存放与映射有关的所有文件,称为映射"

Second I created a folder to hold all files relating to mapping called "Mappings"

第三,我在映射文件夹中的自己文件中设置了Automapper的配置:

Third I set up the configuration of Automapper in its own file in the mappings folder :

public class AutoMapperConfiguration
{
    public MapperConfiguration Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<ViewModelToDomainMappingProfile>();
            cfg.AddProfile<DomainToViewModelMappingProfile>();
            cfg.AddProfile<BiDirectionalViewModelDomain>();
        });
        return config;
    }
}

Forth 还在映射文件夹中自己的文件中,设置了映射配置文件,如下所示:

Forth Also in its own file in the mappings folder I set up the mapping profile as follows:

public class DomainToViewModelMappingProfile : Profile
{
    public DomainToViewModelMappingProfile()
    {
        CreateMap<Client, ClientViewModel>()
           .ForMember(vm => vm.Creator, map => map.MapFrom(s => s.Creator.Username))
           .ForMember(vm => vm.Jobs, map => map.MapFrom(s => s.Jobs.Select(a => a.ClientId)));
    }
}

第五,我还在映射文件夹中添加了一个扩展方法作为其自己的文件...此文件随后在startup.cs中使用:

Fifth, I added an extension method as its own file also in the mappings folder... this was used next in startup.cs:

public static class CustomMvcServiceCollectionExtensions
{
    public static void AddAutoMapper(this IServiceCollection services)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }
        var config = new AutoMapperConfiguration().Configure();
        services.AddSingleton<IMapper>(sp => config.CreateMapper());
    }
}

第六我将此行添加到Startup.cs的ConfigureServices方法中

Sixth I added this line into the ConfigureServices method in Startup.cs

        // Automapper Configuration
        services.AddAutoMapper();

最后,我在控制器中使用它来转换集合...

Finally I used it in a controller to convert a collection...

 IEnumerable<ClientViewModel> _clientVM = Mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);

基于我之前提到的问题,我认为我已经设置了所有内容,因此可以使用它,但是在上面的控制器中,我遇到了错误...

Based on the question I referred to earlier I thought I had everything set so I could use it however I got an error on the line above in the Controller...

映射器未初始化.以适当的配置调用初始化.如果您试图通过容器或其他方式使用映射器实例,请确保您没有对静态Mapper.Map方法的任何调用,并且如果要使用ProjectTo或UseAsDataSource扩展方法,请确保您传入适当的IConfigurationProvider实例."

"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的正确方法吗?我怀疑我在这里错过了一步..非常感谢任何帮助.

What have I missed.. Is this the correct way to set up Automapper? I suspect I am missing a step here.. any help greatly appreciated.

推荐答案

AutoMapper有两种用法:依赖项注入和较旧的static(用于向后兼容).您正在将其配置为进行依赖项注入,但随后尝试使用静态.那是你的问题.您只需要选择一种方法,然后选择另一种即可.

AutoMapper has two usages: dependency injection and the older static for backwards compatibility. You're configuring it for dependency injection, but then attempting to use the static. That's your issue. You just need to choose one method or the other and go with that.

如果要通过依赖项注入来执行此操作,则控制器应将映射器作为构造函数参数保存到成员中,然后需要使用该成员进行映射:

If you want to do it with dependency injection, your controller should take the mapper as a constructor argument saving it to a member, and then you'll need to use that member to do your mapping:

public class FooController : Controller
{
    private readonly IMapper mapper;

    public FooController(IMapper mapper)
    {
        this.mapper = mapper;
    }

然后:

IEnumerable<ClientViewModel> _clientVM = mapper.Map<IEnumerable<Client>, IEnumerable<ClientViewModel>>(_clients);

对于静态方法,您需要使用配置初始化AutoMapper:

For the static method, you need to initialize AutoMapper with your config:

public MapperConfiguration Configure()
{
    AutoMapper.Mapper.Initialize(cfg =>
    {
        cfg.AddProfile<ViewModelToDomainMappingProfile>();
        cfg.AddProfile<DomainToViewModelMappingProfile>();
        cfg.AddProfile<BiDirectionalViewModelDomain>();
    });
}

然后,您只需要在Startup.cs中调用此方法即可;您将不再注册单身人士.

You then need only call this method in Startup.cs; you would no longer register the singleton.

这篇关于自动映射器错误,指出未初始化映射器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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