AutoMapper / AutoMapper.Extensions.Microsoft.DependencyInjection

MIT License
258 stars 79 forks source link

Allow for additional configurations during setup #163

Closed JKamsker closed 2 years ago

JKamsker commented 2 years ago

I have a mechanism, which requires dynamic mapping generation during setup. I have fixed it for me but i'd love to see it in the package. So here is what i did:

services.AddSingleton<IConfigurationProvider>(sp =>
{
    // A mapper configuration is required
    var options = sp.GetRequiredService<IOptions<MapperConfigurationExpression>>().Value;

    foreach (var configurator in sp.GetServices<IAdditionalAutomapperConfigurator>())
    {
        configurator.Apply(options);
    }

    return new MapperConfiguration(options);
});

Instead of ServiceCollectionExtensions.cs#L106#L111

And

public interface IAdditionalAutomapperConfigurator
{
    void Apply(MapperConfigurationExpression options);
}

public class FuncAdditionalAutomapperConfiguratior : IAdditionalAutomapperConfigurator
{
    private readonly Action<MapperConfigurationExpression> configurator;

    public FuncAdditionalAutomapperConfiguratior(Action<MapperConfigurationExpression> configurator)
    {
        this.configurator = configurator;
    }
    public void Apply(MapperConfigurationExpression options)
    {
        configurator(options);
    }
}

public static class AdditionalAutomapperExtensions
{
    public static IServiceCollection AddMapping(this IServiceCollection service, Action<MapperConfigurationExpression> configurator)
    {
        service.AddSingleton<IAdditionalAutomapperConfigurator>(new FuncAdditionalAutomapperConfiguratior(configurator));
        return service;
    }
}

This allows me to call IServiceCollection.AddMapping(cfg => ), which will then be included in the Mapping initialization process. LMK if you want me to do a PR.

lbargaoanu commented 2 years ago

Somebody already did that. There is an overload that works a lot like what you did here.

JKamsker commented 2 years ago

@lbargaoanu Could you please reference the overload you mean?

lbargaoanu commented 2 years ago

I'm afraid they all have the same name. You'll just have to look for it.

github-actions[bot] commented 2 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.