Click here to Skip to main content
15,891,739 members
Articles / Web Development / ASP.NET
Tip/Trick

AutoMapper Auto Profile Configuration

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
2 Jun 2015CPOL 18.6K   1  
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:

C#
// 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:

C#
/// <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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
I've just started out on my career path. I use .NET technologies and JavaScript.

Comments and Discussions

 
-- There are no messages in this forum --