IOptionsMonitor не отслеживает измененияC#

Место общения программистов C#
Anonymous
IOptionsMonitor не отслеживает изменения

Сообщение Anonymous »

У меня есть этот код с конфигурацией InMemory:

Код: Выделить всё

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace ConfigGames
{
internal class MyOptions
{
public string? MyId { get; set; }
}

internal class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddInMemoryCollection(new Dictionary()
{
["Value:MyId"] = Guid.NewGuid().ToString()
});
builder.Services.Configure(builder.Configuration.GetSection("Value"));
builder.Services.AddHostedService();
IHost host = builder.Build();

var runTask = host.RunAsync();

await Task.Delay(1000);

// ################## let's get our value
var opMonitor = host.Services.GetRequiredService();
Console.WriteLine(opMonitor.CurrentValue.MyId);

// ################## and track changes
opMonitor.OnChange(newValue =>
{
Console.WriteLine($"New value: {newValue.MyId}");
});

// ################## trying to change the value
host.Services.GetRequiredService().GetSection("Value")["MyId"] = Guid.NewGuid().ToString();

await Task.Delay(1000);

// ################## now the new value should be there
Console.WriteLine(opMonitor.CurrentValue.MyId);

await Task.Delay(1000);
await host.StopAsync();
await runTask;
}
}
}
Я получаю следующий результат:

Код: Выделить всё

Hello, World!
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Projects\ConfigGames\ConfigGames\bin\Debug\net10.0
d1369bd5-31ee-49a4-8443-1edc50b1f38f
d1369bd5-31ee-49a4-8443-1edc50b1f38f
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...

C:\Projects\ConfigGames\ConfigGames\bin\Debug\net10.0\ConfigGames.exe (process 15488) exited with code 0 (0x0).
Press any key to close this window . . .
Я надеялся на следующее:
  • два разных значения
  • сообщение о новом значении.
Есть идеи?>

Вернуться в «C#»