【问题标题】:Automapper error saying mapper not initializedAutomapper 错误说映射器未初始化
【发布时间】:2022-04-10 22:35:07
【问题描述】:

我正在使用 Automapper 5.2。我以this链接为基础。我将逐步描述我设置 Automapper 的过程。

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

PM> Install-Package AutoMapper

第二我创建了一个文件夹来保存与映射相关的所有文件,称为“映射”

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

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

Forth 同样在 mappings 文件夹中它自己的文件中,我将映射配置文件设置如下:

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)));
    }
}

第五,我在mappings文件夹中也添加了一个扩展方法作为它自己的文件...这是在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 方法中添加了这一行

        // Automapper Configuration
        services.AddAutoMapper();

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

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

根据我之前提到的问题,我认为我已经设置好了所有东西,所以我可以使用它,但是我在 Controller 中的上面一行出现错误...

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

我错过了什么......这是设置 Automapper 的正确方法吗?我怀疑我在这里遗漏了一步。非常感谢任何帮助。

【问题讨论】:

  • 嗨..您找到解决方案了吗?我也面临同样的问题。
  • AutoMapper.Extensions.Microsfot.DependencyInjection 版本 5.0.1 和 AutoMapper 7.0.1 出现此错误。使用 AutoMapper 6.1.1 安装 3.2.0 解决了这个问题,让我正常调用 _mapper.Map。我不知道为什么,据我所知,我没有调用静态 Mapper 类,也没有使用 ProjectTo 或 UseAsDataSource。

标签: c# asp.net-mvc automapper


【解决方案1】:

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

如果你想通过依赖注入来实现它,你的控制器应该将映射器作为构造函数参数保存到一个成员,然后你需要使用该成员来进行映射:

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:

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

然后你只需要在 Startup.cs 中调用这个方法;您将不再注册单例。

【讨论】:

【解决方案2】:

从 autoMapper V9.0 开始,静态 API 不再可用。 或者您可以从 NuGet 包管理器将版本更改为 6.2.2 请参阅此文档confgiration AutoMapper

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。 Automapper 在我的电脑上运行良好。当我部署它时它不起作用,因为我错过了 System.ValueTupple.dll 。

    【讨论】:

      【解决方案4】:

      更好的解决方案是创建这样的扩展方法

        public static DestinationType CastObject<SourceType, DestinationType>(this SourceType obj)
                  {
                      var config = new MapperConfiguration(cfg =>
                      cfg.CreateMap<SourceType, DestinationType>());
      
                      var mapper = config.CreateMapper();
      
                      var entity = mapper.Map<DestinationType>(obj);
      
                      return entity;
                  }
      

      【讨论】:

      • @LucianBargaoanu,这是什么问题,automapper static fucntion不工作,这个解决方案是错误的还是不能工作,你能解释一下吗?
      • @SyedRizwanulHaq,不好的是每次调用该方法时都会定义 AM 配置。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多