2

Wanted to use AutoMapper to deal with some 'monkey' code. It works right of the bat; now looking to set up all the mapping in one place. So, I have:

  1. A static class AutoMapperConfiguration in AppStart folder.
  2. A static Configure method in which I call Mapper.Initialize(). I call Configure() from Global.axax.cs In controller, I proceed to use Mapper.Map(src obj, dest obj). However, this gives me a Unmapped properties exception.

    When I use CreateMap inside a MappingConfiguration variable and do iMapper.Map(), it is working. Is this the right way to do it? If so, how to configure and use it from a single location? Can I use unity container?

Shwrk
  • 173
  • 1
  • 11
  • That exception is just that. You're trying to map an object that hasn't been mapped. – Chase Florell Dec 21 '17 at 11:25
  • Just now, I tried `unityContainer.RegisterInstance(AutoMapperConfiguration.config.CreateMapper());` in unityConfig and injecting the IMapper to controller is working, but I'm not sure how – Shwrk Dec 21 '17 at 11:29

1 Answers1

3

Because I don't want to orphan this question; and for the benefit of any(unlucky) person who ends up on this question; this is what worked for me:

  1. Inside the Configure() in AutoMapperConfiguration class; instead of using the Mapper.Initialize() syntax; I set a property of type MappingConfiguration like

    config = new MapperConfiguration(cfg => { cfg.CreateMap<viewModel1, entity1>(); cfg.CreateMap<viewModel2, entity2>(); etc.. });

2) Next step was to call Configure() from Global.asax.cs

This allowed me to do the following in unityConfig.cs :

unityContainer.RegisterInstance<IMapper>(AutoMapperConfiguration.config.CreateMapper());

What's left is to inject an IMapper instance to my Controller and use it like:

mapper.Map(src obj, dest obj);
Shwrk
  • 173
  • 1
  • 11