c# - 在 N 层应用程序中配置 Automapper

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

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

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

MyApp.DataAccess - 带有 EF 的存储库

MyApp.Domain - 领域/业务模型

MyApp.Services - 服务(类库)

MyApp.Api - ASP.NET Web API

我使用 Unity 作为我的 IoC 容器,使用 Automapper 进行 OO 映射。

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

我不想在我的 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也没有正确回答我的问题。

最佳答案

您需要创建映射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>();
})));

关于c# - 在 N 层应用程序中配置 Automapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635558/

相关文章:

c# - CameraCapture Windows8.1 和 WP 8.1 在 CapturePhotoToStreamAsync 时禁用系统声音

xml - 使用AutoMapper将特定的XML元素从字符串分配给ViewModel

c# - ASP.NET Web API 2 和部分更新

javascript - 为什么向服务器提交对象数据时需要调用JSON.stringify?

c# - 在 .Net Core 2.1 的 XUnit 单元测试中注册 AutoMapper

c# - C# asp.net性能实践中使用static automapper

c# - 无法在PowerShell 3.0和2.0中取消分配内存

c# - 如何在 Cassandra 中获得可靠的插入时间?

c# - 是否可以选择在 Rider 中折叠我的代码?

c# - C# WebApi 中的实时 FLV 流式传输