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();
}