2
votes

So the problem is pretty simple, but I just can't see a way to the solution.

In my solution I have a DAL layer (Class library), a DTO layer (Class library) and an MVC project.

The idea is that the MVC app requests items from the DTO layer, which in turn gets items from the DAL layer. Simple enough.

In the DTO layer I have repositories with a context to manage them. So the MVC app creates an instance of the DTO context, and then gets DTO entities from the appropriate repository.

Now for the problem.

In the DTO layer I use AutoMapper to map the underlying entities to DTOs, and in the MVC app I planned on using it again to map the DTOs to ViewModels and back.

So in the constructor of the context in the DTO layer I call the static RegisterMappings() to register the mappings between the underlying entities and the DTOs. No problems so far.

However in the Global.asax of the MVC app I also call RegisterMappings() (from a different class to the one in the DTO layer) yet when I try to map from a ViewModel to DTO in the MVC app I get the Missing type map configuration or unsupported mapping exception.

On looking at the exceptions thrown by AssertConfigurationIsValid() I can see the automapper is still looking at the mappings between the DAL and DTO layers, not the DTO and MVC app layers as expected.

So how do I use automapper in 2 separate projects within the same solution without getting this "bleeding" effect of mappings?

Any ideas are much appreciated.

1
Are you using AutoMapper 5 or later? Then I think you can store each configuration separately and rather than use the static Mapper calls, use config.CreateMapper(); to create a mapper for each layer. - stuartd
@stuartd change that to an answer lad. Worked perfectly for me. - Barry O'Kane

1 Answers

1
votes

You can keep the mappings separate by storing the AutoMapper configuration in each project, and then using the configuration to create the Mapper:

// DTO project
MapperConfiguration dtoConfig;

dtoConfig = new MapperConfiguration(cfg => {
    cfg.CreateMap<Foo, Bar>();
    cfg.AddProfile<DtoProfile>();
});

// MVC project
MapperConfiguration mvcConfig;

mvcConfig = new MapperConfiguration(cfg => {
    cfg.CreateMap<Foo, Bar>();
    cfg.AddProfile<MvcProfile>();
});

Then when you want to map a class, use the appropriate config to create the mapper:

var mapper = mvcConfig.CreateMapper();
mapper.Map<Foo, Bar>(foo);