[英]Configuring Automapper in N-Layer application
我有一個N層應用程序,如下所示
MyApp.Model - 包含edmx和數據模型
MyApp.DataAccess - 使用EF的存儲庫
MyApp.Domain - 域/業務模型
MyApp.Services - 服務(類庫)
MyApp.Api - ASP.NET Web API
我使用Unity作為我的IoC容器,使用Automapper進行OO映射。
我的DataAccess圖層引用了包含所有Data對象的Model層。
我不想在我的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層中執行,我沒有引用我的模型項目。 我相信我應該在服務層執行此操作但不確定如何執行此操作。 請幫助您如何配置此映射。
注意:在問這里之前我用Google搜索了所有的眼睛
在引用的dll中放置AutoMapper地圖注冊的位置說使用靜態構造函數,我認為不是在我的所有模型中添加一個好選項(我有100個模型)而另一個答案說使用PreApplicationStartMethod我必須添加對System的引用.web.dll到我的服務哪個不正確。
https://groups.google.com/forum/#!topic/automapper-users/TNgj9VHGjwg也沒有正確回答我的問題。
您需要在每個圖層項目中創建映射配置文件 ,然后告訴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>();
})));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.