kema

AutoMapper

Nov 21st, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. using AutoMapper;
  2.     using System;
  3.     using System.Linq;
  4.  
  5.     public class AutoMapperProfile : Profile
  6.     {
  7.         public AutoMapperProfile()
  8.         {
  9.             var allTypes = AppDomain
  10.                 .CurrentDomain
  11.                 .GetAssemblies()
  12.                 .Where(a => a.GetName().Name.Contains("AreasDemo"))
  13.                 .SelectMany(a => a.GetTypes());
  14.  
  15.             allTypes
  16.                 .Where(t => t.IsClass && !t.IsAbstract && t
  17.                     .GetInterfaces()
  18.                     .Where(i => i.IsGenericType)
  19.                     .Select(i => i.GetGenericTypeDefinition())
  20.                     .Contains(typeof(IMapFrom<>)))
  21.                 .Select(t => new
  22.                 {
  23.                     Destination = t,
  24.                     Source = t
  25.                         .GetInterfaces()
  26.                         .Where(i => i.IsGenericType)
  27.                         .Select(i => new
  28.                         {
  29.                             Definition = i.GetGenericTypeDefinition(),
  30.                             Arguments = i.GetGenericArguments()
  31.                         })
  32.                         .Where(i => i.Definition == typeof(IMapFrom<>))
  33.                         .SelectMany(i => i.Arguments)
  34.                         .First(),
  35.                 })
  36.                 .ToList()
  37.                 .ForEach(mapping => this.CreateMap(mapping.Source, mapping.Destination));
  38.  
  39.             allTypes
  40.                 .Where(t => t.IsClass
  41.                     && !t.IsAbstract
  42.                     && typeof(IHaveCustomMapping).IsAssignableFrom(t))
  43.                 .Select(Activator.CreateInstance)
  44.                 .Cast<IHaveCustomMapping>()
  45.                 .ToList()
  46.                 .ForEach(mapping => mapping.ConfigureMapping(this));
  47.         }
  48.     }
Add Comment
Please, Sign In to add comment