0

In my ASP.NET Core application configuration usually doesn't change. So I want to create a typed Options object in ConfigureServices(IServiceCollection services) and add that object as a singleton to the services using services.AddSingleton(typeof(IOptions), configuration.Get<Options>()).

But ASP.NET Core doesn't allow to add additional parameters to the ConfigureServices(IServiceCollection services) method.

So the following isn't possible:


public interface IOptions { ... }
public class Options : IOptions { ... }

...

public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
  services
    .AddSingleton(typeof(IOptions), configuration.Get<Options>())
    .AddControllers();
}

Is there a way to achieve this (i.e. adding an Option object, configured by ASP.NET configuration services, to the services collection)?

AxD
  • 2,714
  • 3
  • 31
  • 53
  • How is “options / configuration” created..? Why is this extra parameter required? Remember IoC has not kicked in yet. – user2864740 Jul 18 '20 at 00:56
  • See above sample code: The `Options` class is a local class. Configuration is supposed to be taken from any configuration provider (e.g. `appsettings.json`). – AxD Jul 18 '20 at 01:17
  • See https://stackoverflow.com/a/32461831/2864740 (build a SP) and https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addsingleton (using a function to generate singleton value), perhaps. I’m not sure if the SC has (or is guaranteed to have) the IConfiguration registered at that point, hence the potential need to defer. – user2864740 Jul 18 '20 at 01:32
  • 1
    D'oh! ... Thank you for linking. I didn't see these yesterday. Today, with a fresh mind, I even noticed that `IConfiguration` is a member of `Startup`, fed by DI. So I don't need to do anything - it's already there. I'll add a corresponding solution to my question. – AxD Jul 18 '20 at 13:19

1 Answers1

1

Solution was close at hand and I overlooked it:

IConfiguration is available as a member field in Startup, so it's already available and no need to provide it again as additional argument:

public class Startup
{
  private readonly IConfiguration _configuration;



  public Startup(IConfiguration configuration) => _configuration = configuration;



  // This method gets called by the runtime. Use this method to add services to the container for dependency injection.
  public void ConfigureServices(IServiceCollection services)
  {
    services
      .AddSingleton<Options>(_configuration.GetSection("AppSettings").Get<Options>())
      .AddControllers();
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Options options)
  {
    Context.ConnectionString = options.DbConStr;
  }
}
AxD
  • 2,714
  • 3
  • 31
  • 53