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

3

我正在使用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中被调用,该类会调用我的automapper配置方法。但我不确定如何从控制器中访问所有这些内容。我读到过一些关于依赖注入的东西,但我不太熟悉这意味着什么,也不知道如何应用它。
我曾经使用过Automapper,但我认为我实现的是不再可用的静态API。其中config方法看起来像这样:
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方法。我需要做什么才能访问我的映射并使用它们?


1
构建映射器并将其注册到应用程序使用的依赖容器中。 - Nkosi
https://docs.automapper.org/en/latest/Dependency-injection.html#examples - Lucian Bargaoanu
1个回答

1
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);

//...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接