Website Summary Files Commits Branches @commit @diff @stats
path: root / src / Common / AutoMapperConfiguration / AutoMapperConfig.cs
blob: 1ca619697f6abec159271915089422f1e04ae60a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AutoMapperConfiguration
{
    public class AutoMapperConfig
    {
        public static IMapper Mapper;

        public static void RegisterMappings(params Type[][] typeCollections)
        {
            MapperConfiguration mapperConfiguration = new MapperConfiguration(mapperConfig =>
            {
                foreach (var typeCollection in typeCollections)
                {
                    foreach (var type in typeCollection)
                    {
                        List<Type> mapFromTypes = type.GetInterfaces()
                            .Where(i => i.Name.Contains("IMapFrom"))
                            .Select(i => i.GetGenericArguments()[0])
                            .ToList();

                        foreach (var fromType in mapFromTypes)
                        {
                            mapperConfig.CreateMap(fromType, type);
                        }
                        
                        List<Type> mapToTypes = type.GetInterfaces()
                            .Where(i => i.Name.Contains("IMapTo"))
                            .Select(i => i.GetGenericArguments()[0])
                            .ToList();

                        foreach (var toType in mapToTypes)
                        {
                            mapperConfig.CreateMap(type, toType);
                        }

                        if(typeof(IHaveCustomMappings).IsAssignableFrom(type))
                        {
                            ((IHaveCustomMappings) Activator.CreateInstance(type)).CreateMappings(mapperConfig);
                        }
                    }
                }
            });

            Mapper = mapperConfiguration.CreateMapper();
        }
    }
}