如何在 ASP.NET MVC 控制器中使用 Automapper 配置

How to use Automapper configuration in ASP.NET MVC controllers

我正在使用 AutoMapper 将我的模型转换为视图模型。我已完成所有设置、测试和工作的配置。作为参考,这是我的配置方法的样子:

    public static MapperConfiguration Configure()
    {
            MapperConfiguration mapperConfiguration = new MapperConfiguration(cfg => {
                cfg.CreateMap<Ebill, EbillHarvesterTaskVM>()
                cfg.CreateMap<Note, NoteVM>();
                cfg.CreateMap<LoginItem, LoginCredentialVM>()
                cfg.CreateMap<Login, ProviderLoginVM>()
            });

            mapperConfiguration.CreateMapper();

            return mapperConfiguration;
     }

这是我的测试结果:

public void ValidConfigurationTest()
{
    var config = AutoMapperConfig.Configure();
    config.AssertConfigurationIsValid();
}

我不明白的是如何访问它以从我的控制器中实际将一个对象映射到另一个对象。我知道我可以在我的应用程序启动时调用此配置方法,我有一个从 global.asax 调用的应用程序配置 class,它调用我的自动映射器配置方法。我不确定如何从控制器中访问所有这些。我读过一些说依赖注入的东西,但我对这意味着什么还不够熟悉,不知道如何应用它。

我过去使用过 Automapper,但我想我实现了现在不可用的静态 API。配置方法如下所示:

public static void RegisterMappings()
    {
        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<ManagementCompany, ManagementCompanyViewModel>();
            cfg.CreateMap<ManagementCompanyViewModel, ManagementCompany>();

        });
    }

配置调用在Global.asax

AutoMapperConfig.RegisterMappings();

以及您可以在控制器中调用它以利用映射的位置:

AutoMapper.Mapper.Map(managementCompany, managementCompanyVM);

这种方式已经行不通了。当我键入 AutoMapperMapper 时,没有要调用的 Map 方法。我需要做什么才能访问我的映射并使用它们?

public static MapperConfiguration Configure() {
        MapperConfiguration mapperConfiguration = new MapperConfiguration(cfg => {
            cfg.CreateMap<Ebill, EbillHarvesterTaskVM>()
            cfg.CreateMap<Note, NoteVM>();
            cfg.CreateMap<LoginItem, LoginCredentialVM>()
            cfg.CreateMap<Login, ProviderLoginVM>()
        });

        return mapperConfiguration;
 }

构建映射器并将其注册到您的应用程序使用的依赖项容器中。

global.asax

MapperConfiguration config = AutoMapperConfig.Configure();;

//build the mapper
IMapper mapper = config.CreateMapper();

//..register mapper with the dependency container used by your application.

myContainer.Register<IMapper>(mapper); //...this is just an oversimplified example

更新您的控制器以通过构造函数注入显式依赖映射器

private readonly IMapper mapper;

public MyController(IMapper mapper, ...) {
    this.mapper = mapper;

    //...
}

并在控制器操作中根据需要调用映射器。

//...

Note model = mapper.Map<Note>(noteVM);

//...