在N层应用程序中配置自动映射
我有一个N层应用程序,如下所示
MyApp.Model – 包含edmx和数据模型
MyApp.DataAccess – 使用EF的存储库
MyApp.Domain – 域/业务模型
MyApp.Services – 服务(类库)
MyApp.Api – ASP.NET Web API
我使用Unity作为我的IoC容器,使用Automapper进行OO映射。
我的DataAccess图层引用了包含所有Data对象的Model层。
我不想在我的Api层中引用我的模型项目。 因此,从服务层返回DomainObjects(业务模型)并映射到API层中的DTO(DTO在API层中)。
我在API层中将domainModel配置为DTO映射,如下所示
public static class MapperConfig { public static void Configure() { Mapper.Initialize( config => { config.CreateMap(); config.CreateMap(); //can't do this as I do not have reference for State which is in MyApp.Model //config.CreateMap(); //config.CreateMap(); }); } }
现在我的问题是如何/在哪里配置我的自动映射器映射以将我的实体模型转换为域模型?
要在我的API层中执行,我没有引用我的模型项目。 我相信我应该在服务层执行此操作但不确定如何执行此操作。 请帮助您如何配置此映射。
注意:在问这里之前我用Google搜索了所有的眼睛
-
在引用的dll中放置AutoMapper地图注册的地方说使用静态构造函数我认为不是一个很好的选项添加到我的所有模型中(我有100个模型)而另一个答案说使用PreApplicationStartMethod我必须添加对System的引用.web.dll到我的服务哪个不对。
-
https://groups.google.com/forum/#!topic/automapper-users/TNgj9VHGjwg也没有正确回答我的问题。
您需要在每个图层项目中创建映射配置文件 ,然后告诉AutoMapper在引用所有较低层的最顶层/最外层(调用)层中使用这些配置文件。 在你的例子中:
MyApp.Model
public class ModelMappingProfile : AutoMapper.Profile { public ModelMappingProfile() { CreateMap(); CreateMap(); } }
MyApp.Api
public class ApiMappingProfile : AutoMapper.Profile { public ApiMappingProfile() { CreateMap(); CreateMap(); } }
MyApp.Services
Mapper.Initialize(cfg => { cfg.AddProfile(); cfg.AddProfile(); });
或者如果您使用DI容器(例如SimpleInjector ):
上述就是C#学习教程:在N层应用程序中配置自动映射分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
container.RegisterSingleton(() => new Mapper(new MapperConfiguration(cfg => { cfg.AddProfile(); cfg.AddProfile(); })));
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012294.html