非静态AutoMapper和ASP.NET MVC [英] Non-static AutoMapper and ASP.NET MVC

查看:88
本文介绍了非静态AutoMapper和ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此问题类似: 在哪里放置AutoMapper.CreateMaps?

建议在哪里放置非静态AutoMapper初始化?

Where is the recommended place to put the non-static AutoMapper initialization?

var map = new MapperConfiguration( cfg => ... ).CreateMapper();

建议在哪里存储地图变量,以便控制器可以访问它?

Where is the recommended place to store the map variable in order for it to be accessible from controllers?

谢谢.

推荐答案

一种好的方法是使用依赖项注入并将映射器注入需要访问它的组件.这种新的AutoMapper方法对于单元测试也非常有用,因为您可以模拟接口.

A good approach to this is to use dependency injection and inject the mapper on your components that need access to it. This new approach to AutoMapper is also great for unit testing, as you can just mock the interfaces.

在我们的例子中,我们使用AutoFaq作为IoC容器,并按以下方式设置AutoMapper:

In our case, we use AutoFaq as a IoC container and have AutoMapper set up like this:

builder.RegisterInstance(AutoMapperConfig.GetConfiguredMapper()).As<IMapper>();

GetConfiguredMapper通过调用MapperConfiguration的CreateMapper方法返回一个IMapper.

The GetConfiguredMapper return an IMapper by calling the CreateMapper method of the MapperConfiguration.

然后您可以让AutoFaq完成所有联结和构造函数注入.

You can then let AutoFaq do all the wireup and constructor injection.

如果您真的想保留旧方法,则始终可以将IMapper包装在应用程序中的静态类中.

If you really want to keep the old approach, you can always wrap the IMapper in a static class in your application.

我绝对更喜欢新版本,因为它使模拟和单元测试我们的代码变得非常简单.

I definitely prefer the new version, as it makes it very simple to mock and unit test our code.

这篇关于非静态AutoMapper和ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆