Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Universal Reflection-Driven MappingProfile for Cleaner DTOs #1167

Closed
ImSk1 opened this issue Apr 18, 2024 · 1 comment
Closed

Implement Universal Reflection-Driven MappingProfile for Cleaner DTOs #1167

ImSk1 opened this issue Apr 18, 2024 · 1 comment

Comments

@ImSk1
Copy link

ImSk1 commented Apr 18, 2024

The current DTO mapping strategy using private nested classes within each DTO can be cumbersome and disorganized, especially as the number of DTOs grows. This makes it so you have to make the default map everytime a DTO is created.

image

I'd suggest a reflection-driven MappingProfile that uses this IMapFrom<> interface. This will automatically register all mappings in the assembly, creating default maps just by using the interface and giving the developer the ability to override if there's a need for a custom map.

Here’s a snippet of the suggested additions:

public class MappingProfile : Profile
    {
        public MappingProfile()
            => this.ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());

        private void ApplyMappingsFromAssembly(Assembly assembly)
        {
            var types = assembly
                .GetExportedTypes()
                .Where(t => t
                    .GetInterfaces()
                    .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)))
                .ToList();

            foreach (var type in types)
            {
                var instance = Activator.CreateInstance(type);

                const string mappingMethodName = "Mapping";

                var methodInfo = type.GetMethod(mappingMethodName)
                                 ?? type.GetInterface("IMapFrom`1")?.GetMethod(mappingMethodName);

                methodInfo?.Invoke(instance, new object[] { this });
            }
        }
    }
  using AutoMapper;

  public interface IMapFrom<T>
  {
      void Mapping(Profile mapper) => mapper.CreateMap(typeof(T), this.GetType());
  }
@ramax495
Copy link
Contributor

This approach was used in this solution before and it had been recently simplified to current manual mapping.
#871

@ImSk1 ImSk1 closed this as not planned Won't fix, can't repro, duplicate, stale Apr 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants