using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; namespace Infrastructure.Configuration { public class EFConfigurationProvider : ConfigurationProvider { private readonly List _configValues; private readonly DbContextOptionsBuilder _builder; public EFConfigurationProvider(Action optionsAction, List configValues) { this._configValues = configValues; this._builder = new DbContextOptionsBuilder(); if (optionsAction != null) { optionsAction(_builder); } ChangeToken.OnChange( () => this.GetReloadToken(), () => { this.Load(true); this.OnReload(); }); } public override void Load() { this.Load(); } private void Load(bool reload = false) { using (var dbContext = GetDbContext()) { if (!reload) { dbContext.Database.EnsureCreated(); } Data = (dbContext.Values.Any() ? dbContext.Values.ToList() : CreateAndSaveDefaultValues(dbContext)).ToDictionary(o => o.Id, o => o.Value); } } private EFConfigurationContext GetDbContext() { var dbContext = new EFConfigurationContext(_builder.Options); return dbContext; } private List CreateAndSaveDefaultValues(EFConfigurationContext dbContext) { dbContext.Values.AddRange(_configValues.ToArray()); dbContext.SaveChanges(); return _configValues; } } }