且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动映射器错误,指出未初始化映射器

更新时间:2022-05-29 23:14:13

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.