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.


Ben Foster

About Me

I'm a software engineer and aspiring entrepreneur with 12+ years experience in the tech industry and have worked with startups and SMB’s in areas such as healthcare, recruitment and e-commerce (I even worked in enterprise, once). I founded my first startup Fabrik in 2011.

I now head up the engineering team at Checkout.com. If you're interested in working in an exciting fin-tech company, drop me a message on Twitter.

Creative Commons Licence