Question

When you create a controller in MVC, you don't have to do any additional registration for it. Same goes with adding areas. As long as your global.asax has an AreaRegistration.RegisterAllAreas() call, no additional setup is necessary.

With AutoMapper, we have to register the mappings using some kind of CreateMap<TSource, TDestination> call. One can do these explicitly with the static Mapper.CreateMap, or by deriving from the AutoMapper.Profile class,overriding the Configure method, and calling CreateMap from there.

It seems to me like one should be able to scan an assembly for classes that extend from Profile like MVC scans for classes that extend from Controller. With this kind of mechanism, shouldn't it be possible to create mappings simply by creating a class that derives from Profile? Does any such library tool exist, or is there something built into automapper?

Was it helpful?

Solution

I don't know if such tool exists, but writing one should be pretty trivial:

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x => GetConfiguration(Mapper.Configuration));
    }

    private static void GetConfiguration(IConfiguration configuration)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (var assembly in assemblies)
        {
            var profiles = assembly.GetTypes().Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x));
            foreach (var profile in profiles)
            {
                configuration.AddProfile((Profile)Activator.CreateInstance(profile));
            }
        }
    }
}

and then in your Application_Start you could autowire:

AutoMapperConfiguration.Configure();

OTHER TIPS

As a slight improvement to the answer from @Darin Dimitrov, in AutoMapper 5 you can give it a list of Assemblies to scan like this:

//--As of 2016-09-22, AutoMapper blows up if you give it dynamic assemblies
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                    .Where(x => !x.IsDynamic);
//--AutoMapper will find all of the classes that extend Profile and will add them automatically    
Mapper.Initialize(cfg => cfg.AddProfiles(assemblies));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top