Can not inject IOptions in service

5.8k views Asked by At

I am trying to inject a IOptions inside a service that I created and it is always null:

public class Startup
{
    private IConfiguration configuration;
    public Startup(IConfiguration config)
    {
        this.configuration = config; //gets injected from Main method , not null !
    }
    public void ConfigureServices(IServiceCollection services)
    {

        Config config = configuration.GetSection("Config").Get<Config>();
        services.Configure<Config>(configuration);
        services.AddTransient<StatusService>();
        services.AddCors();
        services.AddOptions();

    }
}

Service

internal class StatusService
{
    private Config config;
    public StatusService(IOptions<Config>_config)
    {
      this.config=_config.Value; // _config has default fields
    }
}

P.S Config is just a POCO that gets populated in the Program.Main method using UseConfiguration extension.The configuration is parsed OK so no problems there.I get the configuration injected successfully in the Startup constructor.

2

There are 2 answers

0
Joe Audette On BEST ANSWER

your code should be like this:

services.Configure<Config>(configuration.GetSection("Config"));
2
Hasan On

I would suggest you to inject options as a separate class as so that you can get only related types of settings and/or constants all together. Firstly, you should define the options in appsettings.json as shown below.

{
  "Config": {
    "ConfigId": "value",
    "ConfigName": "value",
    "SomeBoolean": true,
    "SomeConstant": 15,
  }
}

After specifying your things in appsettings.json file, you need to create a class to load those values from appsettings.json. In this case it goes as Config.cs details of this class shown below.

public class Config
{
    public string ConfigId { get; set; }
    public string ConfigName { get; set; }
    public bool SomeBoolean { get; set; }
    public int SomeConstant { get; set; }
}

After creating the proper class you can get values onto the class as below. As you might notice IConfiguration is private and gets the whole settings from appsetttings.json just to initilize the application. And, in ConfigureServices() you should get related portion values from that Configuration object to inject other services.

private IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
      Configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{               
     services.Configure<Config>(Configuration.GetSection("Config"));
}

After configuring your options class (Config.cs), you can inject it as IOptions as shown below.

private readonly Config _config;
public StatusService(IOptions<Config> config)
{
     _config = config.Value;
}  

Hope this solves your problem.