【问题标题】:Mapper does not contain a definition for Initialize AutoMapper C#Mapper 不包含 Initialize AutoMapper C# 的定义
【发布时间】:2020-01-13 17:39:45
【问题描述】:

我在我的 asp.net C# 项目中实现了 Auto Mapper,但出现错误:

Mapper 不包含 Initialize 的定义

我试过这个例子Link Here

我已经粘贴了我的代码:

namespace NewsWeb.Web.Infrastructure
{
    public class AutomapperWebProfile:Profile
    {
        public AutomapperWebProfile()
        {
            CreateMap<DistrictDTO, District>().ReverseMap();
        }

        public static void Run()
        {
            Mapper.Initialize(a =>
            {
                a.AddProfile<AutomapperWebProfile>();
            });
        }
    }
}

在我的 Gobal.asax.cs 文件中:

 AutomapperWebProfile.Run();

错误图片:

【问题讨论】:

标签: c# asp.net-mvc automapper


【解决方案1】:

方法 Mapper.Initialize 自版本 v9.0.0 (doc) 起已过时,您需要改用 MapperConfiguration (doc)。

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<AutomapperWebProfile>();
});

var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);

在 Golbal.asax 中使用静态方法初始化映射器不是一个灵活的解决方案。我建议直接在自定义映射器类中创建一个配置。

public interface IFooMapper 
{   
    Foo Map(Bar bar); 
}

public class FooMapper : IFooMapper
{
    private readonly IMapper mapper;

    public FooMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<FooProfile>();
        });

        mapper = config.CreateMapper();
    }

    public Foo Map(Bar bar) => mapper.Map<Foo>(bar);
}

【讨论】:

  • 如何在 Global.asax 文件中使用它?
  • 我已经添加了这个问题的答案。
猜你喜欢
  • 2022-09-23
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多