AxD
AxD

Reputation: 3158

How can I add Option object as service?

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)?

Upvotes: 0

Views: 2586

Answers (1)

AxD
AxD

Reputation: 3158

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;
  }
}

Upvotes: 1

Related Questions