Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reading appsettings.json expensive?

Currently I'm developing a .net core 2 application that should read some keys from appsettings.json on each request based on domain. (I have to mention, I have a single solution with 3 projects that share the same appsettings.json) I'm concerned about the reading time of the appsettings.json file on each request. Does this file get cached when the app starts? My Startup consrtuctor is the following :

public IConfiguration Configuration { get; }
private readonly ILoggerFactory _logger;

public Startup(IHostingEnvironment env, ILoggerFactory logger)
        {
            string settingPath = Path.GetFullPath(Path.Combine(@"../SharedConfig/globalAppSettings.json"));
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile(settingPath)
                .AddEnvironmentVariables();

            Configuration = builder.Build();

            _logger = logger;
        }
like image 570
Coder Avatar asked Jan 18 '18 08:01

Coder


Video Answer


1 Answers

Configuration API constructs key and values using IConfigurationBuilder.Build method that builds IConfiguration with keys and values from the set of sources registered before.

If briefly, the following mechanism is implemented:

  • Internally the specific provider is used to read from the registered source. File-based sources have the appropriate FileConfigurationProvider. For JSON files this is a JsonConfigurationProvider.
  • IConfigurationBuilder.Build method constructs providers for each of registered sources and calls the provider.Load method.
  • Load reads data from the source and fill an internal Provider.Data collection (dictionary to be more specific) of key-value pairs.
  • This Data collection is then used by Configuration API when you need to get a value by key in your app.

When Configuration API creates the FileConfigurationProvider instance, it uses the value of FileConfigurationSource.ReloadOnChange property (false by default). If this property is true, then provider subscribes to "file changed" event (in ctor) to call Load each time when the file is changed (and so repopulate the Data collection. From github:

if (Source.ReloadOnChange && Source.FileProvider != null)
{
    ChangeToken.OnChange(
         () => Source.FileProvider.Watch(Source.Path),
         () => {
                  Thread.Sleep(Source.ReloadDelay);
                  Load(reload: true);
               });
}
like image 150
Set Avatar answered Nov 14 '22 15:11

Set