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.CreateMap<Source, Destination>();

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

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.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in AutoMapper. Bookmark the permalink. Follow any comments here with the RSS feed for this post.