Profile picture Schedule a Meeting
c a n d l a n d . n e t

Setting Up AutoMapper For Use From A Container

Dusty Candland | |

I like getting all my service from the container and I like using AutoMapper. So I added the AutoMapper to the container, a WindsorContainer in this case.

The main interface is IMappingEngine, which is implemented by MappingEngine which also implements IMappingEngineRunner. This contains a getter to an IConfiguration interface which is also an IConfigurationExpression. So to replace Mapper you need an instance of IMappingEngine and then you can configure the engine as follows:

public CustomMapper(IMappingEngine engine)

{

    engine = engine;

 

    var runner = engine as IMappingEngineRunner;

    if (runner == null)

        return;

 

    var configuration = runner.Configuration as IConfigurationExpression;

    if (configuration == null)

        return;

 

    configuration.CreateMap<IApplication, B.Application>();

}

Next setting up the container, the MappingEngine needs an IConfiguration, the Configuration needs some IObjectMapper instances.

private static void RegisterMappingEngine()

{

    container.Register(AllTypes.Of<IObjectMapper>()

                            .FromAssembly(typeof (IObjectMapper).Assembly)

                            .Configure(configurer => configurer.Named(configurer.ServiceType.Name))

                            .Configure(configurer => configurer.LifeStyle.Transient));

 

    container.Register(Component.For<IConfiguration>().ImplementedBy<Configuration>()

                            .LifeStyle.Transient.ServiceOverrides(

                            ServiceOverride.ForKey("mappers").Eq(

                                "CustomTypeMapMapper",

                                "TypeMapMapper",

                                "NewOrDefaultMapper",

                                "StringMapper",

                                "EnumMapper",

                                "ArrayMapper",

                                "EnumerableMapper",

                                "NullableMapper",

                                "AssignableMapper")

                            ));

 

    _container.Register(Component.For<IMappingEngine>().ImplementedBy<MappingEngine>()

                            .LifeStyle.Transient);

}

These are all set as Transient because each CustomMapper can be Singleton and I don’t want the mappings to over lap between the CustomMappers.

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: