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:
var types = typeof(Program).Assembly.GetTypes();
var automapperProfiles = types
.Where(x => x.IsSubclassOf(typeof(Profile)))
.Select(Activator.CreateInstance)
.OfType<Profile>()
.ToList();
automapperProfiles.ForEach(Mapper.Configuration.AddProfile);
It works a treat.
AutoMapper Extension
So now I've factored it out into an extension class:
public static class AutoMapperExtensions
{
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.