Non-static AutoMapper and ASP.NET MVC

蓝咒 提交于 2019-12-13 01:45:09

问题


Similarly to this question: Where to place AutoMapper.CreateMaps?

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?

Thanks in advance.


回答1:


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.

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

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

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

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

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.



来源:https://stackoverflow.com/questions/37319320/non-static-automapper-and-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!