I have a ASP.Net Web API that was using Automapper 7.0.1 with static mappings. I recently upgraded to Automapper 9.0.0 which does not have static mappings. So, I used the recommended way of using my Dependency Container (Unity Container) to register the instances of IMapper and IConfigurationProvider as Singletons.
var config = AutoMapperConfig.GetMapperConfiguration();
_container.RegisterInstance<IConfigurationProvider>(config, new SingletonLifetimeManager());
_container.RegisterInstance<IMapper>(new Mapper(config), new SingletonLifetimeManager());
The AutoMapperConfig.GetMapperConfiguration() is a static method that returns a new Config with all the mappings.
public static MapperConfiguration GetMapperConfiguration()
{
return new MapperConfiguration(config =>
{
config.CreateMap<MyDtoReq, MyModel1>(MemberList.Destination);
config.CreateMap<MyModel1, MyDtoRes>(MemberList.Destination);
// other mappings
}
}
Therafter, I have resolved and used IMapper in numerous services which are registered with PerRequestLifetimeManager, like:
_container.RegisterType<IService1, Service1>(new PerRequestLifetimeManager());
I can see that the Unity resolved both Services and Mapper properly, but when I call Map() using:
_service1.Mapper.Map<MyDtoRes>(myModel1ObjectInstance);
It gives me an AutoMapperException saying
Missing type map configuration or unsupported mapping error
I have tried many things inclduding, registering the AutoMapper objects as PerRequest dependencies, even as Singletons using a static class (without DI container) but to no avail.
I am sure that my mappings are correct because they worked with Static AutoMapper in v 7.0.1. What have I missed out after the upgrade?
Turns out that that there were 2 problems.
I needed to use a
Profilecontaining all the mappings. So I moved all the mappings from theMapperConfigurationto aProfileas followsAnd then, use the
MapperConfigurationExpressionas followsThere were some mappings that were missing (only 2) which worked in the older version probably because automatic mappings were enabled in it by default. The newer version 9.0.0 showed the exact missing mappings only after I moved them to the
Profile.