1

Can I get access to the AutoMapper configuration instance when using assembly scanning to register the profiles. https://docs.automapper.org/en/latest/Dependency-injection.html

I had previously used ForAllMaps() to add a generic IgnoreUnmappedProperties() for all mappings.

public static class AutoMapperExtensions
{
    private static void IgnoreUnmappedProperties(TypeMap map, IMappingExpression expr)
    {
        foreach (string propName in map.GetUnmappedPropertyNames())
        {
            if (map.SourceType.GetProperty(propName) != null)
            {
                expr.ForSourceMember(propName, opt => opt.Ignore());
            }
            if (map.DestinationType.GetProperty(propName) != null)
            {
                expr.ForMember(propName, opt => opt.Ignore());
            }
        }
    }

    public static void IgnoreUnmapped(this IProfileExpression profile)
    {
        profile.ForAllMaps(IgnoreUnmappedProperties);
    }

    public static void IgnoreUnmapped(this IProfileExpression profile, Func<TypeMap, bool> filter)
    {
        profile.ForAllMaps((map, expr) =>
        {
            if (filter(map))
            {
                IgnoreUnmappedProperties(map, expr);
            }
        });
    }

    public static void IgnoreUnmapped(this IProfileExpression profile, Type src, Type dest)
    {
        profile.IgnoreUnmapped((TypeMap map) => map.SourceType == src && map.DestinationType == dest);
    }

    public static void IgnoreUnmapped<TSrc, TDest>(this IProfileExpression profile)
    {
        profile.IgnoreUnmapped(typeof(TSrc), typeof(TDest));
    }

}

I am not seeing how I might add this in the new DI pattern. Can someone point me to the docs I need to accomplish this, or tell me I'm dumb and should use this other pattern to achieve the same thing? : o)

Josh Russo
  • 3,080
  • 2
  • 41
  • 62

1 Answers1

2

There are overrides of .AddAutoMapper() that accept an Action<IMapperConfigurationExpression> or even Action<IServiceProvider, IMapperConfigurationExpression> as the first argument.

For instance:

    private static void ConfigureAutoMapper(this IServiceCollection services)
    {
        services.AddAutoMapper(
           config => config.ForAllMaps(IgnoreUnmappedProperties),
           new List<Assembly> { typeof(AutoMapperExtensions).Assembly });
    }

eduherminio
  • 1,514
  • 1
  • 15
  • 31