Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

AutoMapper Auto Profile Configuration

0.00/5 (No votes)
2 Jun 2015 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:

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here