想要使用 AutoMapper 来处理一些“猴子”代码。它在球棒的右侧起作用;现在希望将所有映射设置在一处。所以,我有:
- AppStart 文件夹中的静态类 AutoMapperConfiguration。
- 一个静态配置方法,我在其中调用 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?
最佳答案
因为我不想孤立这个问题;以及为了任何最终解决这个问题的(不幸的)人的利益;这对我有用:
在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/