I think itโs too late to answer the question, but maybe someone can use my answer.
I use Ninject to resolve dependencies, so I created the Ninject Module for AutoMapper. Here is the code:
public class AutoMapperModule : NinjectModule { public override void Load() { Bind<IConfiguration>().ToMethod(context => Mapper.Configuration); Bind<IMappingEngine>().ToMethod(context => Mapper.Engine); SetupMappings(Kernel.Get<IConfiguration>()); Mapper.AssertConfigurationIsValid(); } private static void SetupMappings(IConfiguration configuration) { IEnumerable<IViewModelMapping> mappings = typeof(IViewModelMapping).Assembly .GetExportedTypes() .Where(x => !x.IsAbstract && typeof(IViewModelMapping).IsAssignableFrom(x)) .Select(Activator.CreateInstance) .Cast<IViewModelMapping>(); foreach (IViewModelMapping mapping in mappings) mapping.Create(configuration); } }
As you can see when loading, it scans the assembly to implement IViewModelMapping, and then runs the Create method.
Here is the IViewModelMapping code:
interface IViewModelMapping { void Create(IConfiguration configuration); }
A typical implementation of IViewModelMapping is as follows:
public class RestaurantMap : IViewModelMapping { public void Create(IConfiguration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); IMappingExpression<RestaurantViewModel, Restaurant> map = configuration.CreateMap<RestaurantViewModel, Restaurant>();
Alexander Romanov
source share