。Net Core解决方案中每个项目的Automapper不同配置文件

问题描述 投票:1回答:1

我有一个具有以下结构的.Net Core 2.1解决方案

基础结构(在这里添加了自动映射器)<< ApplicationCore(大多数逻辑服务在这里)<< MVC

基础结构(在此处添加了自动映射器)<< ApplicationCore(大多数逻辑服务在这里)<

(只是为了清除Infrastructure&ApplicationCore类库项目仅存在一次)

ApplicationCore,MVC和Web API项目都具有特定于它们的类/ DTO /视图模型。因此,在MVC和/或API项目的启动文件中只有一个配置文件是可以的,但是会涉及一些重复。

也用于测试,我想在没有MVC或API项目的情况下运行ApplicationCore。

是否有一个很好的示例项目,说明每个项目如何具有不同的配置文件?

c# .net-core automapper asp.net-core-2.1
1个回答
1
投票

我有同样的问题。这是我的解决方案,

  1. 我在应用程序核心库中继承了'Profile'创建了'MapperProfiles'

    public class MapperProfiles : Profile
    {
        public MapperProfiles()
        {
            CreateMap<YourModel, YourViewModel>();
            CreateMap<YourViewModel, YourModel>();
        }
    }
    
  2. 在以下行中添加了startup.cs,

    services.AddAutoMapper(typeof(MapperProfiles));
    
  3. 现在将控制器修改为,

    private readonly IMapper _mapper;
    
    public YourController(ApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }
    
  4. 现在您可以在控制器中使用映射器,

    YourModel model = _mapper.Map<YourModel >(YourViewModel);
    
© www.soinside.com 2019 - 2024. All rights reserved.