AutoMapper 2.0 – Nested/Child Containers
One of the major features introduced with the AutoMapper 2.0 release is the ability to support nested/child containers. Service location has been in AutoMapper for a while now, but its scope was limited to configuration time:
Mapper.Initialize(cfg => { cfg.ConstructServicesUsing(ObjectFactory.GetInstance); cfg.CreateMap<Source, Destination>(); });
</p>
While this works, we can see above that I have to use a static service locator function to construct all supporting mapping objects AutoMapper uses (Formatters, Resolvers and Type Converters). This becomes an issue with child/nested containers, where I’m building up a specific container instance with specific scope and configuration.
In order to support this scenarios, AutoMapper allows you to pass in a custom service locator at map time, instead of configuration time:
var dest = Mapper.Map<Source, Destination>(new Source { Value = 15 }, opt => opt.ConstructServicesUsing(childContainer.GetInstance));
</p>
Where the “childContainer” is an individual container instance. Since the scope of resolving instances is narrowed to each mapping call, you can supply individual containers for service location for each mapping operation.