Skip to content

Instantly share code, notes, and snippets.

@jessejjohnson
Created October 4, 2021 19:11
Show Gist options
  • Save jessejjohnson/0f31782692b6fabe89f8f31c6dae48b2 to your computer and use it in GitHub Desktop.
Save jessejjohnson/0f31782692b6fabe89f8f31c6dae48b2 to your computer and use it in GitHub Desktop.
AutoMapper Domain Mapping Profiles
using AutoMapper;
namespace Application.Common.Mappings
{
public interface IMapFrom<T>
{
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
}
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