Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - IOptions pattern with default dynamic value not working as expected

I have a class which contains my configuration of a StartDate string, it is a yyyyMMdd hh:mm:ss representation of a timestamp, this string can be passed through appsettings or environment variables as normal with ASP.NET applications, but when it is not set, I would like it to return the current time.

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

In my Startup I register this configuration class like so:

public class Startup
{
    public IConfiguration Configuration { get; }

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

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

I then inject it in another service and use it like so:

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

My AppSettings(.Development).json nor environment variables contain a value for MyOptions.StartDate

Whenever I call SomeOtherClass.SomeFunction(), it will keep returning whatever the timestamp was when my app first started.

I have split the StartDate property in MyOptions into a separate getter and setter class, and noticed the setter is being hit while the application starts. It seems it's reading the initial return value from DateTime.Now.ToString("yyyyMMdd hh:mm:ss"), but then setting this value, causing the set value to returned in any consecutive get call.

What am I missing to get it to return the current timestamp whenever it is called?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to get it working using the code like below

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

the appsettings.json should have MyOptions element like below

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

Please check that environment name matches with environment specific appsettings if you are modifying not the global appsettings.json file. It means that environment name have to be Development if appsettings.Development.json has MyOptions configuration element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...