无法在服务中注入IOptions [英] Can not inject IOptions in service

查看:145
本文介绍了无法在服务中注入IOptions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将IOptions注入我创建的服务中,并且始终为空:

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();

    }
}

服务

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

PS Config只是使用UseConfiguration扩展名在Program.Main方法中填充的POCO.配置被解析为OK,所以没有问题.我在Startup构造函数.

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.

推荐答案

您的代码应如下所示:

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

这篇关于无法在服务中注入IOptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆