如何将 Automapper 与统一依赖注入一起使用?

How to use Automapper with unity dependancy injection?

我打算将 Automapper 与 ASP.NET MVC 解决方案和 Unity DI 一起使用。 automapper 上发布的关于如何使用的视频很旧,没有展示映射器如何与依赖注入一起使用。 Whosebug 上的大多数示例还使用 Mapper.CreateMap() 方法,该方法现已弃用。

自动映射器指南说

Once you have your types you can create a map for the two types using a MapperConfiguration instance and CreateMap. You only need one MapperConfiguration instance typically per AppDomain and should be instantiated during startup.

 var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());

所以我假设上面的代码行将进入应用程序启动,比如 global.asax

要执行映射,请使用 CreateMapper 方法创建 IMapper。

 var mapper = config.CreateMapper();
 OrderDto dto = mapper.Map<OrderDto>(order);

以上行将进入控制器。但是我不明白这个 config 变量来自哪里?如何在控制器中注入 IMapper?

首先,创建一个 MapperConfiguration 并从中创建一个 IMapper,其中所有类型都配置如下:

var config = new MapperConfiguration(cfg =>
{
    //Create all maps here
    cfg.CreateMap<Order, OrderDto>();

    cfg.CreateMap<MyHappyEntity, MyHappyEntityDto>();

    //...
});

IMapper mapper = config.CreateMapper();

然后,像这样在统一容器中注册映射器实例:

container.RegisterInstance(mapper);

然后,任何希望使用映射器的控制器(或服务)都可以像这样在构造函数中声明这种依赖关系:

public class MyHappyController
{
    private readonly IMapper mapper;

    public MyHappyController(IMapper mapper)
    {
        this.mapper = mapper;
    }

    //Use the mapper field in your methods
}

假设您使用 MVC 框架正确设置了容器,控制器应该可以毫无问题地构建。