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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…