下面是.NET Core控制台应用程序的示例,它与IOptionsSnapshot<T>
一起使用构造函数依赖项注入。
class Program
{
static void Main(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json",
optional: false, reloadOnChange: true)
.Build();
IServiceProvider provider = new ServiceCollection()
.Configure<AppSettings>(
configuration.GetSection("AppSettings"))
.AddTransient<CheckOption>()
.BuildServiceProvider();
while (true)
{
if (Console.ReadLine() != "stop")
{
CheckOption checkOption =
provider.GetRequiredService<CheckOption>();
checkOption.Run();
}
else
{
return;
}
}
}
}
public class CheckOption
{
public AppSettings _AppSettings;
public CheckOption(IOptionsSnapshot<AppSettings> appSettings)
{
_AppSettings = appSettings.Value;
}
public void Run()
{
string option1 = _AppSettings.Option1;
string option2 = _AppSettings.Option2;
}
}
public class AppSettings
{
public string Option1 {get; set;}
public string Option2 {get; set;}
}
在while循环中更改“ appsettings.json”后,Option1
和Option2
的值保持不变。