在ASP.NET MVC应用程序中在Global.asax级别配置最新版本的AutoMapper

Bla*_*ell 2 c# asp.net-mvc automapper

我试图弄清楚如何在Global.asax级别配置新的AutoMapper。

我以前使用旧的AutoMapper执行以下操作:

在App_Start文件夹中创建一个名为MappingProfile.cs的类,并在构造函数中添加如下所示的映射:

public MappingProfile()
{
     Mapper.CreateMap<Product, ProductDto>();
     Mapper.CreateMap<ApplicationUser, UserDto>();
}
Run Code Online (Sandbox Code Playgroud)

然后在Global.asax中调用:

Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何使用新版本的AutoMapper实现上述目标吗?我一直在阅读文档,但似乎无法理解。

我相信我在MappingProfile.cs文件中做了这样的事情:

    var config = new MapperConfiguration(cfg =>
    {
       cfg.CreateMap<Product, ProductDto>();
       cfg.CreateMap<ApplicationUser, UserDto>();
    });
Run Code Online (Sandbox Code Playgroud)

但是我该如何使用config变量?

Int*_*NET 5

这就是我的方法。

public abstract class AutoMapperBase
{
    protected readonly IMapper _mapper;

    protected AutoMapperBase()
    {
        var config = new MapperConfiguration(x =>
        {
            x.CreateMap<Product, ProductDto>();
            x.CreateMap<ApplicationUser, UserDto>();
        });

        _mapper = config.CreateMapper();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后从需要使用它的任何类继承AutoMapperBase,并按如下方式调用它:

var foo = _mapper.Map<ProductDto>(someProduct);
Run Code Online (Sandbox Code Playgroud)

您不再需要在Global.asax中声明或配置它

  • 好的,所以我创建了您的 AutoMapperBase 类,现在在 ApiController 中,如果该类已经从 ApiController 继承,我该如何使用它。多重继承只允许通过接口 (2认同)