.net core .NET核心全局变量未获取初始设置

.net core .NET核心全局变量未获取初始设置,.net-core,asp.net-core-mvc,.net Core,Asp.net Core Mvc,我正在创建一个全局变量,但首先需要用数据初始化它。变量似乎正在工作,但未设置初始化数据。这是我的ConfigureServices public void ConfigureServices(IServiceCollection services) { services.AddOptions(); //Gets data for the Global variable MyOptions opt = SetValues(); Action<MyOptions

我正在创建一个全局变量,但首先需要用数据初始化它。变量似乎正在工作,但未设置初始化数据。这是我的
ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    //Gets data for the Global variable
    MyOptions opt = SetValues();
    Action<MyOptions> options = (set => set = opt);
    services.Configure(options);
    services.Configure<MyOptions>(options);
    services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<MyOptions>>().Value);
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void配置服务(IServiceCollection服务)
{
services.AddOptions();
//获取全局变量的数据
MyOptions opt=SetValues();
操作选项=(设置=>set=opt);
服务。配置(选项);
服务。配置(选项);
services.AddSingleton(解析器=>resolver.GetRequiredService().Value);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
然后在不同的控制器中,我这样称呼它

public ValuesController(IOptions<MyOptions> options)
{
    Options = settings.Value;
}
公共价值控制器(选项)
{
选项=设置值;
}

在测试中,控制器可以更改
选项中的属性,但是,设置是在
MyOptions opt=SetValues()中完成的不存在。我做错了什么?

我认为在这种情况下没有必要使用内置选项模式

此代码不使用其优点(例如,从appsettings读取设置)

您可以将MyOptions实例注册为单例,而无需使用IOptions包装器(如下所示)

services.AddSingleton(opt);
使用此功能的更好方法是将设置中的选项放入appsetting.json


谢谢你,我做到了!