doorman
doorman

Reputation: 16959

How to access DI inside custom ConfigurationProvider

I am implementing a custom ConfigurationProvider and I have the following extension method in place

 public static class ConfigurationExtensions
    {
        public static IConfigurationBuilder AddConfigProviderConfiguration(this IConfigurationBuilder configuration)
        {
            configuration.Add(new ConfigurationSource());
            return configuration;
        }
    }

And I am calling the extension method like this

return new ServiceCollection().AddConfigProviderServices()

This is the ConfigurationSource class

 public class ConfigurationSource : IConfigurationSource
    {
        public IConfigurationProvider Build(IConfigurationBuilder builder)
        { 
            return new ConfigurationProvider(this);
        }
    }

Inside the ConfigurationProvider I would like to be able to inject or somehow access dependencies like ILogger, that I have registered as DI. How can I access the dependencies?

Upvotes: 4

Views: 2502

Answers (1)

doorman
doorman

Reputation: 16959

I ended up adding another load method inside the ConfigurationProvider class that takes in IServiceProvider as a parameter like this:

  public class ConfigurationProvider : Microsoft.Extensions.Configuration.ConfigurationProvider
    {
        public void Load(IServiceProvider serviceProvider)
        {
            var logger = serviceProvider.GetRequiredService<ILogger<ConfigurationProvider>>();
// Get other services using serviceProvider, e.g. dbContext and call  Set(s.Key, s.Value); accordingly

Next call the custom load method after ServiceProvier has been initiated and pass it in as a parameter like this:

[TestInitialize()]

    public void InitializeTest()
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory
                .GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddConfigProviderConfiguration()
            .Build();
    
        serviceProvider = ServiceProvider.BuildDi(config);
        
        var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
        loggerFactory.AddProvider(new LoggerProvider(config));
    
        var provider = config.Providers.FirstOrDefault(p => p is ConfigurationProvider);
        var cp = (ConfigurationProvider)provider;
        cp.Load(serviceProvider);
    }

Not the nicest solution but it works and all the DI dependencies are accessible from within ConfigurationProvider.

Upvotes: 2

Related Questions