Search code examples
asp.net-mvcreflectionautomapperautomapper-2auto-registration

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?


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();