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

前端 未结 3 1088
夕颜
夕颜 2020-12-17 16:25

I have an console application (in dot net core 1.1) which is scheduled in cron scheduler for every 1 min. Inside the application there is call to configuration file. I\'m a

3条回答
  •  醉话见心
    2020-12-17 17:16

    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(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(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(new ConfigurationManager(this.Configuration));
    

    and inject it into your services via constructor

提交回复
热议问题