October 12, 2011

AutoMapper StructureMap Profile

Get rid of that static Mapper reference and inject a mapper into your services with StructureMap.

Below is an updated StructureMap registry to wire up all the bits of AutoMapper 2.0 for dependency injection:

public class AutomapperRegistry : Registry
{
    public AutomapperRegistry()
    {
        For<ConfigurationStore>().Singleton().Use<ConfigurationStore>()
            .Ctor<IEnumerable<IObjectMapper>>().Is(MapperRegistry.AllMappers());
        For<IConfigurationProvider>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
        For<IConfiguration>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
        For<ITypeMapFactory>().Use<TypeMapFactory>();
        For<IMappingEngine>().Use<MappingEngine>();

        Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.AddAllTypesOf<Profile>();
        });
    }
}

When you need an AutoMapper mapper, just add a constructor dependency of type IMappingEngine.

You’ll need to configure when your application starts. Here’s my bootstrapper:

public static class AutoMapperBootstrapper
{
    private static readonly IConfiguration cfg = ObjectFactory.GetInstance<IConfiguration>();
    
    public static void Initialize()
    {
        cfg.AddProfile<MyAutoMapperProfile>();
    }

    public class MyAutoMapperProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<SomeEntity, SomeViewModel>();
        }
    }
}

Then we just call AutoMapperBootstrapper.Initialize() in global.asax.

Simple.

© 2022 Ben Foster