Created
October 4, 2021 19:11
-
-
Save jessejjohnson/0f31782692b6fabe89f8f31c6dae48b2 to your computer and use it in GitHub Desktop.
AutoMapper Domain Mapping Profiles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using AutoMapper; | |
namespace Application.Common.Mappings | |
{ | |
public interface IMapFrom<T> | |
{ | |
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using AutoMapper; | |
namespace Application.Mappings | |
{ | |
public class MappingProfile : Profile | |
{ | |
private const Type InterfaceType = typeof(IMapFrom<>); | |
private const string InterfaceName = "IMapFrom`1"; | |
private const string MethodName = "Mapping"; | |
public MappingProfile() | |
{ | |
ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); | |
} | |
private void ApplyMappingsFromAssembly(Assembly assembly) | |
{ | |
var types = FindImplementationTypes(assembly, InterfaceType); | |
foreach (var type in types) | |
{ | |
var instance = Activator.CreateInstance(type); | |
var methodInfo = type.GetMethod(MethodName) ?? type.GetInterface(InterfaceName).GetMethod(MethodName); | |
methodInfo?.Invoke(instance, new object[] { this }); | |
} | |
} | |
private static IEnumerable<Type> FindImplementationTypes(Type interface, Assembly assembly) => | |
assembly.GetExportedTypes() | |
.Where(t => t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interface)) | |
.ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment