Error while reading json file in dotnet core "the configured user limit (128) on the number of inotify instances has been reached"

var builder = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.json", true, true);

You are creating file watchers, every time you access an setting. The 3rd parameter is reloadOnChange.

You have to make sure,

var configuration = builder.Build()

is only called once in your application and store it in a place where you can access it (preferably AVOID static fields for it).

Or just disable the file watcher.

  var builder = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.json", true, false);

or cleaner:

var builder = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: false);

Best way is to abstract that behind an interface and use dependency injection.

public interface IConfigurationManager
{
    T GetAppConfig<T>(string key, T defaultValue = default(T));
}

public class ConfigurationManager : IConfigurationManager
{
    private readonly IConfigurationRoot config;

    public ConfigurationManager(IConfigurationRoot config)
        => this.config ?? throw new ArgumentNullException(nameof(config));

    public T GetAppConfig<T>(string key, T defaultValue = default(T))
    {
        T setting = (T)Convert.ChangeType(configuration[key], typeof(T));
        value = setting;
        if (setting == null)
            value = defaultValue;
    }
}

Then instantiate and register it

services.AddSingleton<IConfigurationManager>(new ConfigurationManager(this.Configuration));

and inject it into your services via constructor


The reason why error the configured user limit (128) on the number of inotify instances has been reached happens is right - on non Windows environment reloadOnChange cause the issue while accessing appSetting.json files.

But there is a think you could miss while adjusting this. I addition to setting reloadOnChange to false:

.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: false);

you should also make sure you are not starting from default WebHost.CreateDefaultBuilder because inside it reloadOnChange is also set to true. So the best way to control what your web host is would be to configure it from scratch without not needed options (e.g. WebHost.CreateDefaultBuilder also does .UseIISIntegration() which probably don't need at all in your environment).

The example of custom web host - a copy of Microsoft WebHost.CreateDefaultBuilder but with IIS and FileWatcher dependencies removed e.g. for Linux environments.