在N层应用程序中配置Automapper

6

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

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

MyApp.DataAccess - 使用EF的存储库

MyApp.Domain - 领域/业务模型

MyApp.Services - 服务(类库)

MyApp.Api - ASP.NET Web API

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

我的DataAccess层引用包含所有数据对象的Model层。

我不想在Api层中引用我的model项目。因此,从服务层返回DomainObjects(业务模型),并在API层将其映射到DTOs(DTOs在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. 在引用的dll中放置AutoMapper映射注册的位置说要使用静态构造函数,但我认为这不是一个好的选择,因为我有100个模型,另一个答案建议使用PreApplicationStartMethod,但这需要将System.web.dll添加到我的服务中,这是不正确的。 2. https://groups.google.com/forum/#!topic/automapper-users/TNgj9VHGjwg也没有正确回答我的问题。

"实体模型" → 你只提到了一次,我们怎么知道呢? - aaron
http://docs.automapper.org/en/stable/Configuration.html#profile-instances - Lucian Bargaoanu
@aaron 抱歉。"实体模型"是由edmx生成器创建的MyApp.Model项目中的类。 - aditya
@LucianBargaoanu 谢谢你的链接,我会尝试并回复你。 - aditya
@LucianBargaoanu 那有什么帮助吗? - Ian Kemp
该页面解释了如何在需要AM的模块的应用程序中配置AM。 - Lucian Bargaoanu
1个回答

4
您需要在每个层项目中创建映射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>();
});

如果您正在使用依赖注入容器(例如SimpleInjector):

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

现在已经内置了探测功能,这将是最简单的方法。当然,您也可以让 DI 容器来完成这个任务。 - Lucian Bargaoanu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接