2

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help. We're also in the process of doing this refactoring, so the ideas are still pretty fresh. My only concern is having only one instance of the mapper for the entire application, I'm curious to see how it escalates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.