簡體   English   中英

具有默認動態值的 IOptions 模式未按預期工作

[英]IOptions pattern with default dynamic value not working as expected

我有一個 class ,其中包含我對StartDate字符串的配置,它是時間戳的yyyyMMdd hh:mm:ss表示形式,此字符串可以像 ASP.NET 應用程序一樣通過 appsettings 或環境變量傳遞,但如果未設置,我希望它返回當前時間。

public class MyOptions
{
    public string StartDate { get; set; } = DateTime.Now.ToString("yyyyMMdd hh:mm:ss");
}

在我的啟動中,我像這樣注冊此配置 class :

public class Startup
{
    public IConfiguration Configuration { get; }

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

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

然后我將它注入另一個服務並像這樣使用它:

public class SomeOtherService
{
    private readonly MyOptions _options;
    public SomeOtherService(IOptions<MyOptions> options)
    {
        _options = options.Value;
    }
    
    void SomeFunction()
    {
        Console.WriteLine($"StartDate is: {_options.StartDate}");
    }
}

我的 AppSettings(.Development).json 環境變量也不包含MyOptions.StartDate的值

每當我調用SomeOtherClass.SomeFunction()時,它都會繼續返回我的應用程序首次啟動時的時間戳。

我已將MyOptions中的StartDate屬性拆分為單獨的 getter 和 setter class,並注意到在應用程序啟動時 setter 被擊中。 似乎它正在從DateTime.Now.ToString("yyyyMMdd hh:mm:ss")讀取初始返回值,但隨后設置此值,導致在任何連續的 get 調用中返回設置值。

我錯過了什么讓它在被調用時返回當前時間戳?

我能夠使用下面的代碼讓它工作

services.Configure<MyOptions>(_ => Configuration.GetSection("MyOptions").Bind(_));

appsettings.json應該有如下MyOptions元素

"MyOptions": {"StartDate": "test"}

如果您修改的不是全局appsettings.json文件,請檢查環境名稱是否與特定於環境的 appsettings 匹配。 這意味着如果appsettings.Development.json具有MyOptions配置元素,則環境名稱必須是Development

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM