0

I have written an extension for the ServiceCollection in which I want to configure my EntityFramework Core configuration and the respective DbContext. Loading the configuarion via a json-file works. Now, the part where I am struggling is that I want to map my IInstanceConfiguration to my OracleConfiguration, as a full instance. My current solution looks like this. I added two comments where I would like to know the correct ( / better ) way to implement this.

Kind regards!

public static void RegisterEfCoreOracle<T>(this IServiceCollection services, string configurationDirectory, string configurationFile) where T : DbContext
    {
        //Adding configuration file
        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(configurationDirectory)
            .AddJsonFile(configurationFile, optional: false)
            .Build();

        services.Configure<OracleConfiguration>(configuration);

        //Do i really have to do it manually this way? What would be another, elegant way?
        var oraInstance = new OracleConfiguration(configuration.GetValue<string>("Name"), configuration.GetValue<string>("DataSource"), configuration.GetValue<string>("UserId"),
            configuration.GetValue<string>("Password"),configuration.GetValue<bool>("UseConsoleLogging"), configuration.GetValue<string>("Compatibility"));

        //This is the line where I am struggling.
        services.AddSingleton<IInstanceConfiguration, OracleConfiguration>(oraInstance);

        var oraConfig = services.ReturnServiceProvider().GetRequiredService<OracleConfiguration>();
        services.AddDbContext<T>();
    }

    public static ServiceProvider ReturnServiceProvider(this IServiceCollection services) => services.BuildServiceProvider();
Insight
  • 196
  • 1
  • 13
  • 1
    See the options pattern: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2 – Mark PM Apr 15 '19 at 10:54

1 Answers1

0

The var oraInstance line is completely unnecessary, line services.Configure<OracleConfiguration>(configuration); should be setting up the dependency injection as expected.

If the type you're injecting into is expecting IInstanceConfiguration specifically instead of the concrete OracleConfiguration, you can register it like so:

services.AddSingleton<IInstanceConfiguration>(sp => 
    sp.GetRequiredService<OracleConfiguration>());

Otherwise, if you have control over the type it's being injected into, it would be best to remove the IInstanceConfiguration interface altogether, and have it accept IOptions<OracleConfiguration> instead.

Matthew
  • 24,703
  • 9
  • 76
  • 110