Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic discovery of automapper configurations

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?

like image 639
danludwig Avatar asked Dec 20 '22 18:12

danludwig


2 Answers

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();
like image 143
Darin Dimitrov Avatar answered Jan 08 '23 11:01

Darin Dimitrov


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));
like image 33
jakejgordon Avatar answered Jan 08 '23 10:01

jakejgordon