Rob L
Rob L

Reputation: 3303

When migrating to AutoMapper 4.2/5.0, should I store an IMapper instance or the MapperConfiguration instance in my dependency injection container?

I am migrating to the newer configuration of AutoMapper. I was looking at examples on the AutoMapper GitHub Wiki and am a little confused on how to complete the configuration. The Wiki says in one place you can store the MapperConfiguration instance in your D.I. container (or store it statically), but the next paragraph says you can store the Mapper instance statically. In a nutshell, I am not sure if I should be doing

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Foo, Bar>().ReverseMap(); //creates a bi-directional mapping between Foo & Bar
    cfg.AddProfile<FooProfile>(); //suppose FooProfile creates mappings...
});

then using a D.I. container such as Unity to store that instance as such...

container.RegisterInstance<MapperConfiguration>(config);

Where I could later use this instance to perform mappings...

public void CreateMapping(MapperConfiguration config, Bar bar)
{
     Foo foo = config.CreateMapper().Map(bar);
     //do stuff with foo
}

or, should I be storing the IMapper instance the MapperConfiguration makes

container.RegisterInstance<IMapper>(config.CreateMapper());

which would have the usage as follows

public void CreateMapping(IMapper mapper, Bar bar)
{
     Foo foo = mapper.Map(bar);
     //do stuff with foo
}

All I will be doing in my application after the initial configuration is calling the Map method. I will not need to modify the configuration. Should I store the IMapper instance or the MapperConfiguration instance in my dependency injection container?

Update: I ended up with registering IMapper with my D.I. container. In my case, Unity.

Upvotes: 3

Views: 3038

Answers (1)

James
James

Reputation: 1058

I don't see why you couldn't store both. I have cases where I need to inject one or the other or both, as I use MapperConfiguration for LINQ projections and IMapper for doing the mapping itself. My IoC registrations look like this:

public static Container RegisterAutoMapper(this Container container)
{
    var profiles = typeof(AutoMapperRegistry).Assembly.GetTypes().Where(t => typeof(Profile).IsAssignableFrom(t)).Select(t => (Profile)Activator.CreateInstance(t));

    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });

    container.RegisterSingleton<MapperConfiguration>(() => config);
    container.RegisterSingleton<IMapper>(() => container.GetInstance<MapperConfiguration>().CreateMapper());

    return container;
}

}

As the IMapper object can be created by the MapperConfiguration, my IoC is spawning an IMapper instance from the current registration of MapperConfiguration.

Upvotes: 2

Related Questions