ASP.Net Core 2.0 中的 AutoMapper

AutoMapper in ASP.Net Core 2.0

有人知道是否有任何方法可以将 AutoMapper 与 ASP.Net Core 2.0 一起使用吗? IServiceCollection 没有扩展。

还有一个可选问题,有没有人尝试过将 AutoMapper 与 .Net Framework 4.7 或 .Net Standard 2.0 一起使用?

事实证明你需要同时添加:
- AutoMapper
- AutoMapper.Extensions.Microsoft.DependencyInjection
或者只有第二个(依赖于第一个)。

您可以创建一个 AutoMapperProfile.cs,然后像下面的代码一样添加到 startup.cs

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<Abc, AbcEntity>();
    }              
}

添加到 startup.cs

中的 ConfigureServices 方法
//Automapper profile
Mapper.Initialize(cfg => cfg.AddProfile<AutoMapperProfile>());

如上所述,您需要 AutoMapper 和 AutoMapper.Extensions.Microsoft.DependencyInjection Nuget 包。

然后在您的 Startup ConfigureServices 方法中,如果您只是使用以下方式添加服务:

services.AddAutoMapper();

这将扫描执行上下文中的所有程序集,查找继承 Automapper.Profile class 的 classes 并自动将它们添加到 AutoMapper 配置中。