繁体   English   中英

在N层应用程序中配置自动映射

[英]Configuring Automapper in N-Layer application

我有一个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<StateModel, StateDto>();
                config.CreateMap<StateDto, StateModel>();

                //can't do this as I do not have reference for State which is in MyApp.Model
                //config.CreateMap<State, StateModel>();
                //config.CreateMap<StateModel, State>();
            });
    }
}

现在我的问题是如何/在哪里配置我的自动映射器映射以将我的实体模型转换为域模型?

要在我的API层中执行,我没有引用我的模型项目。 我相信我应该在服务层执行此操作但不确定如何执行此操作。 请帮助您如何配置此映射。

注意:在问这里之前我用Google搜索了所有的眼睛

  1. 在引用的dll中放置AutoMapper地图注册的位置说使用静态构造函数,我认为不是在我的所有模型中添加一个好选项(我有100个模型)而另一个答案说使用PreApplicationStartMethod我必须添加对System的引用.web.dll到我的服务哪个不正确。

  2. https://groups.google.com/forum/#!topic/automapper-users/TNgj9VHGjwg也没有正确回答我的问题。

您需要在每个图层项目中创建映射配置文件 ,然后告诉AutoMapper在引用所有较低层的最顶层/最外层(调用)层中使用这些配置文件。 在你的例子中:

MyApp.Model

public class ModelMappingProfile : AutoMapper.Profile
{
    public ModelMappingProfile()
    {
        CreateMap<StateModel, StateDto>();
        CreateMap<StateDto, StateModel>();
    }
}

MyApp.Api

public class ApiMappingProfile : AutoMapper.Profile
{
    public ApiMappingProfile()
    {
        CreateMap<State, StateModel>();
        CreateMap<StateModel, State>();
    }
}

MyApp.Services

Mapper.Initialize(cfg => 
{
    cfg.AddProfile<MyApp.Model.ModelMappingProfile>();
    cfg.AddProfile<MyApp.Model.ApiMappingProfile>();
});

或者如果您使用DI容器(例如SimpleInjector ):

container.RegisterSingleton<IMapper>(() => new Mapper(new MapperConfiguration(cfg => 
{
    cfg.AddProfile<MyApp.Model.ModelMappingProfile>();
    cfg.AddProfile<MyApp.Model.ApiMappingProfile>();
})));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM