映射配置文件实例不创建

Mapping profile instance doesn't creates

我正在尝试添加带有反射的自动映射模型,我创建了一个接口 IMapFrom<> 并在所有 dto 中实现了它。 然后我创建了 class

public class MappingProfile : Profile
{
    public MappingProfile(Assembly assembly)
        => ApplyMappingsFromAssembly(assembly);

    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 });
        }
    }
}

并将其添加到服务集合中

public static IServiceCollection AddAutoMapperProfile(IServiceCollection services, Assembly assembly)
         => services
             .AddAutoMapper(
                 (_, config) => config
                     .AddProfile(new MappingProfile(Assembly.GetCallingAssembly())),
                 Array.Empty<Assembly>());

为什么没有创建class实例?因此,我无法将模型转换为 dto

这样试试:

定义 IMapFrom:

public interface IMapFrom<T>
    {
        void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
    }

然后添加映射配置文件:

public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            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);

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

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

            }
        }
    }

创建DI方法:

public static IServiceCollection AddAutoMapperProfile(this IServiceCollection services)
        {

            var assembly = Assembly.GetExecutingAssembly();
            services.AddAutoMapper(assembly);
            return services;
        }

最后调用您创建的 DI 方法:

...
services.AddAutoMapperProfile();
...