c# - Mapper 不包含 Initialize AutoMapper C# 的定义
问题描述
我在我的 asp.net C# 项目中实现了 Auto Mapper,但出现错误:
Mapper 不包含 Initialize 的定义
我试过这个例子链接在这里
我已经粘贴了我的代码:
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();
解决方案
方法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);
在 Gobal.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);
}
推荐阅读
- r - 格式化起点和终点数据
- javascript - 切换数组中的对象而不创建新数组
- selenium - 范围报告:在并行执行测试时,测试步骤正在范围报告中的最后一个测试中合并
- google-cloud-firestore - 在 Angular 服务中映射来自 Firestore 的文档参考字段
- mongodb - 添加多个键/值
- excel - Excel vba:将字符串转换为日期时间将其添加到新列
- java - @Schedule 启动两次
- electron - 重命名电子打包器生成的 .zip 文件
- c# - 在文本框上绘制矩形
- node.js - 将 AwaitReactions 的结果传递到函数 discord.js 之外