Shwrk
Shwrk

Reputation: 173

Setting up AutoMapper(6.2.2) first time in .NET Project

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?

Upvotes: 2

Views: 1499

Answers (1)

Shwrk
Shwrk

Reputation: 173

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);

Upvotes: 3

Related Questions