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

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.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

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 Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.