我有一个 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 层中执行,我没有引用我的模型项目。我相信我应该在服务层执行此操作,但不确定该怎么做。请帮助如何配置此映射。
注意:在这里提问之前,我用所有的眼睛用谷歌搜索
Where to place AutoMapper map registration in referenced dll说要使用静态构造函数,我认为这不是添加到我所有模型中的好选择(我有 100 个模型),另一个答案说要使用 PreApplicationStartMethod,为此我必须将对 System.web.dll 的引用添加到我的服务中,这是不正确。
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/