C# 在.Net核心解决方案中为每个项目自动映射不同的配置文件

C# 在.Net核心解决方案中为每个项目自动映射不同的配置文件,c#,.net-core,automapper,asp.net-core-2.1,C#,.net Core,Automapper,Asp.net Core 2.1,我有一个.NETCore2.1解决方案,其结构如下 基础设施(这里添加了automapper)我也有同样的问题。这是我的解决办法 我在继承“配置文件”的应用程序核心库中创建了“MapperProfiles” public class MapperProfiles : Profile { public MapperProfiles() { CreateMap<YourModel, YourViewModel>(); CreateMap&l

我有一个.NETCore2.1解决方案,其结构如下


基础设施(这里添加了automapper)我也有同样的问题。这是我的解决办法

  • 我在继承“配置文件”的应用程序核心库中创建了“MapperProfiles”

    public class MapperProfiles : Profile
    {
        public MapperProfiles()
        {
            CreateMap<YourModel, YourViewModel>();
            CreateMap<YourViewModel, YourModel>();
        }
    }
    
  • 现在控制器修改为

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

    YourModel model = _mapper.Map<YourModel >(YourViewModel);
    
    YourModel=\u mapper.Map(YourViewModel);
    

  • “Infrastructure(此处添加了automapper)”,但此项目没有DTO/View引用,为什么要在此处添加autumapper配置文件?因此,您可以在任何需要的地方使用配置文件。只要您从Profile类派生,.NetCore的AutoMapper包将嗅探所有程序集并添加您的概要文件,以便它们可以通过IMapper获得injection@LucianBargaoanu,我看过那个项目,但(在我看来)automapper正在web项目的启动文件中设置。我还想在ApplicationCore项目中对其进行配置,以便能够独立于其他web和API项目进行测试。我遗漏了什么吗?@Jinish听起来不错,有关于这是如何工作的文档吗?我一直使用映射器。初始化并传入配置文件。在类库项目(应用程序核心)中,我有一个配置文件,但无法确定如何让我的班级知道它在那里。
    YourModel model = _mapper.Map<YourModel >(YourViewModel);