c# - 首次在.NET项目中设置AutoMapper(6.2.2)

标签 c# .net automapper-6

想要使用 AutoMapper 来处理一些“猴子”代码。它在球棒的右侧起作用;现在希望将所有映射设置在一处。所以,我有:

  1. AppStart 文件夹中的静态类 AutoMapperConfiguration。
  2. 一个静态配置方法,我在其中调用 Mapper.Initialize()。我从 Global.axax.cs 调用Configure() 在 Controller 中,我继续使用 Mapper.Map(src obj, dest obj)。但是,这给了我一个未映射的属性异常。

    When I use CreateMap inside a MappingConfiguration variable and do iMapper.Map(), it is working. Is this the right way to do it? If so, how to configure and use it from a single location? Can I use unity container?

最佳答案

因为我不想孤立这个问题;以及为了任何最终解决这个问题的(不幸的)人的利益;这对我有用:

  1. 在AutoMapperConfiguration类的Configure()内部;而不是使用 Mapper.Initialize()句法;我设置了 MappingConfiguration 类型的属性,例如

    config = new MapperConfiguration(cfg => { cfg.CreateMap<viewModel1, entity1>(); cfg.CreateMap<viewModel2, entity2>(); etc.. });

2) 下一步是从 Global.asax.cs 调用Configure()

这允许我在 unityConfig.cs 中执行以下操作:

unityContainer.RegisterInstance<IMapper>(AutoMapperConfiguration.config.CreateMapper());

剩下的就是将 IMapper 实例注入(inject)到我的 Controller 中并按如下方式使用它:

mapper.Map(src obj, dest obj);

关于c# - 首次在.NET项目中设置AutoMapper(6.2.2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923482/

相关文章:

.net - TransactionScope 和多线程

c# - 如何在 Azure 上获取正确的用户代理 header ?

c# - 为什么.NET 不将参数值添加到异常消息中,例如在 int.Parse 中

c# - 如何从数组中获取所有可能的组合?

c# - AutoMapper 覆盖递归类型

asp.net - 自动映射器-映射器已初始化错误

c# - 没有 setter 的 Automapper 嵌套集合

c# - Protobuf.net 异常 - 检查元数据时超时

c# - 如何匹配自定义 PropertyGrid BrowsableAttributes 条目?

c# - .NET Micro 框架和不受支持的功能。有什么影响?