AutoMapper Auto Profile Configuration





5.00/5 (2 votes)
How to automatically add your AutoMapper profiles
The Scene
I've been using AutoMapper for a while now, about 8 months ago I progressed to using the `Profile` classes to define Mappings. Now I'm just about to go and create these profiles - all over the place - in an old project and don't want to have to be remembering all the profiles I created.
The last thing I wanted to do is have to list all the profiles that I have and add them to the `Mapper.Configuration` manually. Well, you know, Auto is in the name.
Initial Crack
So my initial crack at this is:
// Get all types in the current assembly
var types = typeof(Program).Assembly.GetTypes();
// IsSubclassOf will make sure that we using class deriving Profile
// Activator.CreateInstance will instantiate the profile
// OfType<Profile>() will cast the types
var automapperProfiles = types
.Where(x => x.IsSubclassOf(typeof(Profile)))
.Select(Activator.CreateInstance)
.OfType<Profile>()
.ToList();
// Here we call the static Mapper class and add each profile
automapperProfiles.ForEach(Mapper.Configuration.AddProfile);
It works a treat.
AutoMapper Extension
So now I've factored it out into an extension class:
/// <summary>
/// The auto mapper extensions.
/// </summary>
public static class AutoMapperExtensions
{
/// <summary>
/// The register configurations.
/// </summary>
/// <param name="types">
/// The types.
/// </param>
public static void RegisterConfigurations(this Type[] types)
{
var automapperProfiles = types
.Where(x => x.IsSubclassOf(typeof(Profile)))
.Select(Activator.CreateInstance)
.OfType<Profile>()
.ToList();
automapperProfiles.ForEach(Mapper.Configuration.AddProfile);
}
}
Conclusion
Pretty straightforward but IMHO very powerful! Another one of coding's little helpers to make life considerably easier.