【问题标题】:Configuring Automapper in N-Layer application在 N 层应用程序中配置 Automapper
【发布时间】:2018-06-01 03:07:23
【问题描述】:

我有一个如下所示的 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>();
            });
    }
}

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

在我的 API 层中,我没有参考我的模型项目。我相信我应该在服务层这样做,但不知道该怎么做。请帮助如何配置此映射。

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

  1. Where to place AutoMapper map registration in referenced dll 说要使用静态构造函数,我认为在我的所有模型中添加它不是一个好选择(我有 100 个模型),另一个答案说要使用 PreApplicationStartMethod,我必须为此添加对 System 的引用.web.dll 到我的服务,这是不正确的。

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

【问题讨论】:

  • “实体模型” → 你只提过一次,我们怎么知道?
  • @aaron 对不起。 “实体模型”是由 edmx 生成器创建的 MyApp.Model 项目中的类。
  • @LucianBargaoanu 感谢您的链接,我们会尝试并回复您。
  • @LucianBargaoanu 这有什么帮助?

标签: c# asp.net-web-api automapper n-tier-architecture


【解决方案1】:

您需要在每个层项目中创建映射profiles,然后告诉 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>();
})));

【讨论】:

  • 现在探测是内置的,所以这将是最简单的方法。当然你可以让 DI 容器来做。
猜你喜欢
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多