Using AutoMapper with Castle Windsor in a much cleaner DI friendly way

Hackered
Monday, February 29, 2016
by Sean McAlinden

I have been hooking up AutoMapper with Castle Windsor the same way for many years now.

Whilst the setup has always been functional, the static nature was never great and quite often the static Mapper.Map code ends up littered throughout the codebase.

The setup is now much more DI and unit test friendly.

Registering the Mapper

The following code creates and registers a new mapper:

public class Installer : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IMapper>().UsingFactoryMethod(x =>
            {
                return new MapperConfiguration(c =>
                {
                    c.AddProfile<EntityToViewModelProfile>();
                    c.AddProfile<ViewModelToEntityProfile>();
                }).CreateMapper();
            }));
    }
}

As you can see I am registering the interface IMapper in a Castle Windsor installer, a factory method is then utilized for creating the new MapperConfiguration.

My mapper profiles 'EntityToViewModelProfile' and 'ViewModelToEntityProfile' are added to the MapperConfiguration constructor.

Using the Mapper

Now the mapper is registered we can simply utilize it by injecting it into our class constructors for example:

private readonly IMapper mapper;

public MyClass(IMapper mapper)
{
    this.mapper = mapper;
}

Summary

As you can see, this is a much cleaner and more testable approach.

C#