Custom configuration provider with sqlserver

Salvatore Sanollo 25 Reputation points
2023-03-27T11:11:05.1166667+00:00

Hi everyone,

I need to create my own customized provider configuration with a sqlserver database in order to offer my client (who manages his website) to change some settings.

My idea is to use the settings in the json file for the "system" settings, while I would use the "frontend" settings (e.g. website title) in the sqlserver db.

I found something on the internet but I should be using the transient pattern to always fetch the always up to date data.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,191 Reputation points
    2023-03-28T20:48:27.5233333+00:00

    This is the approach I would go with considering your use case.

        public class ConfigValue
        {
            public string Id { get; set; } = String.Empty;
            public string Value { get; set; } = String.Empty;
        }
    
        public interface ICustomConfigurationService
        {
            void AddConfig(string key, string value);
            string GetValue(string key);
            void RefreshCache();
        }
    
        public class CustomConfigurationService : ICustomConfigurationService
        {
            private readonly ApplicationDbContext _context;
            private readonly IMemoryCache _cache;
            public CustomConfigurationService(ApplicationDbContext context,
                IMemoryCache memoryCache)
            {
                _context = context;
                _cache = memoryCache;
            }
    
            public string GetValue(string key)
            {
                List<ConfigValue> results = new List<ConfigValue>();
                if (!_cache.TryGetValue("config", out results))
                {
                    results = _context.ConfigValues.ToList();
    
                    // Save data in cache.
                    var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(4));
                    _cache.Set("config", results, cacheEntryOptions);
                }
    
                return results.FirstOrDefault(c => c.Id == key).Value;
            }
    
            public void AddConfig(string key, string value)
            {
                ConfigValue config = new ConfigValue()
                {
                    Id = key,
                    Value = value
                };
    
                _context.ConfigValues.Add(config);
                RefreshCache();
            }
    
            public void RefreshCache()
            {
                List<ConfigValue> results = _context.ConfigValues.ToList();
                var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(4));
                _cache.Set("config", results, cacheEntryOptions);
            }
        }
    

    Registration

    builder.Services.AddScoped<ICustomConfigurationService, CustomConfigurationService>();
    

    Implementation

        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
            private readonly ICustomConfigurationService _config;
    
            public HomeController(ILogger<HomeController> logger, ICustomConfigurationService config)
            {
                _logger = logger;
                _config = config;
            }
    
            public IActionResult Index()
            {
                var configSettingValue = _config.GetValue("Title");
                ViewBag.ConfigTitle = configSettingValue;
                return View();
            }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2023-03-28T22:01:39.77+00:00

    a custom configuration provider is added to configuration build at startup and is available to an injected IConfiguration instance.

    the trick to understand is that configuration is a pipeline. all the providers are called when resolving a configuration query. being called in order allows a provider to override another provider.

    so you could define a default in the appsetting.json, and an override in the custom provider.

    note: while it look like a hierarchy in the json, configuration is really a simple name/value pair.

    0 comments No comments