在 N 层应用程序中配置 Automapper

adi*_*tya 5 c# n-tier-architecture automapper asp.net-web-api

我有一个 N 层应用程序,如下所示

MyApp.Model - 包含 edmx 和数据模型

MyApp.DataAccess - 带有 EF 的存储库

MyApp.Domain - 域/业务模型

MyApp.Services - 服务(类库)

MyApp.Api - ASP.NET Web API

我使用 Unity 作为我的 IoC 容器和Automapper用于 OO 映射。

我的 DataAccess 层引用了包含我所有数据对象的模型层。

我不想在我的 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>();
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

Ian*_*emp 4

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

我的应用程序模型

public class ModelMappingProfile : AutoMapper.Profile
{
    public ModelMappingProfile()
    {
        CreateMap<StateModel, StateDto>();
        CreateMap<StateDto, StateModel>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序API

public class ApiMappingProfile : AutoMapper.Profile
{
    public ApiMappingProfile()
    {
        CreateMap<State, StateModel>();
        CreateMap<StateModel, State>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序服务

Mapper.Initialize(cfg => 
{
    cfg.AddProfile<MyApp.Model.ModelMappingProfile>();
    cfg.AddProfile<MyApp.Model.ApiMappingProfile>();
});
Run Code Online (Sandbox Code Playgroud)

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

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