How to reload appsettings.json at runtime every time it changes in .NET core 1.1 console app?

I tried to reproduce the method described in this great Andrew Lock article . However, I cannot run this in a .NET core 1.1 console application. When the file is appsettings.json

modified and saved, the changes are not reflected in the application without restarting.

There are multiple files, so I created the smallest example I could think of on github . I've also provided details in the README.MD file on github.

Any help in resolving this would be most appreciated. Please keep in mind that I am a newbie to the .NET core and not an experienced developer. And this is my first question on stackoverflow ... Thanks in advance!

+3


source to share


1 answer


The key to understanding is scope.

ASP.NET Core has three scopes - transitional, cloud, and single. IOptionsSnapshot

configured as a restricted service.

In ASP.NET core, the launcher is triggered on every request, so every request you get a new instance IOptionsSnapshot

with updated configuration values.

In the above example, you create IServiceProvider

and retrieve an instance IMyService

directly from the top-level provider:

IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();


while (true)
{
    var service = serviceProvider.GetService<IMyService>();
    var reply = service.DoSomething();

    Console.WriteLine(reply);
}

      



Basically, you always use the same scope for every service provider request, so you always get the same instance IOptionsSnapshot

. Effectively, if you never create a new scope, all your scoped services become single-handed!

The fix is ​​to create a new realm every time the service is received:

IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();


while (true)
{
    using (var scope = serviceProvider.CreateScope())
    {
        var service = scope.ServiceProvider.GetService<IMyService>();
        var reply = service.DoSomething();

        Console.WriteLine(reply);
    }
}

      

This also becomes important if you are doing things like creating EF Core DbContext

outside of the request context in an ASP.NET Core app (or in a console app). Always create a new hotspot before accessing services from a service provider!

PS I created a delete request to fix your sample :)

+4


source







All Articles