问题
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