c# - Mapper 不包含 Initialize AutoMapper C# 的定义

标签 c# asp.net-mvc automapper

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

Mapper does not contain a definition for 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>();
            });
        }
    }
}

在我的 Golbal.asax.cs 文件中:
 AutomapperWebProfile.Run();

错误图像:
enter image description here

最佳答案

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

关于c# - Mapper 不包含 Initialize AutoMapper C# 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713215/

相关文章:

c# - Linq 未按预期执行

c# - Automapper 忽略第一个源字段字母

c# - 最大长度不起作用 Web API 2 模型

c# - 如何在 ASP.NET 中将下拉列表与字符串数组绑定(bind)?

c# - MVC4 中@Html.Textbox 的验证

asp.net-mvc - LINQ to EF 有什么问题?

c# - 如何回答请求但继续处理 WebApi 中的代码

c# - Visual Studio 减慢应用程序

c# - Automapper - 更新现有实例

asp.net-core - 在 AutoMapper 配置文件中获取登录用户