using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.EntityFrameworkCore; namespace Hncore.Infrastructure.EF { public static class AutoMapExtensions { private static object syncRoot = new object(); private static ConcurrentDictionary maps; public static void AutoMap(this ModelBuilder modelBuilder, Type assType) { if (maps == null) { lock (syncRoot) { if (maps == null) { maps = new ConcurrentDictionary(); Type mappingInterface = typeof(IEntityMap<>); var mappingTypes = assType.GetTypeInfo().Assembly.GetTypes() .Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface)); foreach (var map in mappingTypes.Select(Activator.CreateInstance).Cast()) { maps.TryAdd(map, null); } } } } foreach (var map in maps.Keys) { map.Map(modelBuilder); } } } }