Can not inject IOptions in service

有些话、适合烂在心里 提交于 2019-11-28 11:03:47

问题


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.


回答1:


your code should be like this:

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



回答2:


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.



来源:https://stackoverflow.com/questions/53897184/can-not-inject-ioptions-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!