Skip to content

Instantly share code, notes, and snippets.

@d2funlife
Last active July 25, 2021 14:58
Show Gist options
  • Save d2funlife/fce02e3898755da5339668a0b53192ba to your computer and use it in GitHub Desktop.
Save d2funlife/fce02e3898755da5339668a0b53192ba to your computer and use it in GitHub Desktop.
Свой источник конфигурации Entity Framework
public class ConfigValue
{
public string Key { get; set; }
public string Value { get; set; }
}
public class EfConfigurationProvider : ConfigurationProvider
{
public Action<DbContextOptionsBuilder> OptionsAction { get; }
public EfConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
{
OptionsAction = optionsAction;
}
public override void Load()
{
var builder = new DbContextOptionsBuilder<ExampleContext>();
OptionsAction(builder);
using var dbContext = new ExampleContext(builder.Options);
Data = dbContext.Configurations.ToDictionary(x => x.Key, v => v.Value);
}
}
public class EfConfigurationSource : IConfigurationSource
{
private readonly Action<DbContextOptionsBuilder> _optionsAction;
public EfConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
{
_optionsAction = optionsAction;
}
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new EfConfigurationProvider(_optionsAction);
}
}
public static class EfExtensions
{
public static IConfigurationBuilder AddEfConfiguration(this IConfigurationBuilder configurationBuilder,
Action<DbContextOptionsBuilder> optionsAction)
{
return configurationBuilder.Add(new EfConfigurationSource(optionsAction));
}
}
public class ExampleContext : DbContext
{
public DbSet<ConfigValue> Configurations { get; set; }
public ExampleContext(DbContextOptions options) : base(options)
{
}
}
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context,
builder) =>
{
var config = builder.Build();
builder.AddEfConfiguration(optionsBuilder =>
{
optionsBuilder.UseNpgsql(config.GetConnectionString("DatabaseConnection"));
});
})
.UseStartup<Startup>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment