I am building an ASP.NET Core WebApi service using Entity Framework Core and the Simple Injector IoC Container. The application use a postgresql DB via Npgsql.EntityFrameworkCore.PostgeSQL.
Here is a code snippet from my Startup and ServicesInstaller:
public class Startup
{
public IConfiguration Configuration { get; }
private IConfigurationRoot configurationRoot;
private Container container;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
// Build configuration info
configurationRoot = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true,
reloadOnChange: true)
.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Initialize Container
container = new SimpleInjector.Container();
container.Options.ResolveUnregisteredConcreteTypes = false;
container.ConfigureServices();
services.AddSimpleInjector(container, options =>
{
options.AddAspNetCore()
.AddControllerActivation();
options.AddLogging();
});
}
}
ServicesInstaller:
public static class ServicesInstaller
{
public static void ConfigureServices(this Container container)
{
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
//Assembly.Load will not re-load already loaded Assemblies
container.Register<IFooContext, FooContext>(Lifestyle.Scoped);
container.Register<FooContext>(Lifestyle.Scoped);
}
}
Here is a code snippet from my DB Context class:
public interface IFooContext
{
}
public class FooContext : DbContext, IFooContext
{
public FooContext()
{
}
protected override void OnConfiguring(
DbContextOptionsBuilder optionbuilder)
{
optionbuilder.UseNpgsql(
"Server=.;Port=5432;Database=...;User ID=...;Password=...;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Currently I'm hardwiring my connection string to the PostGreSQL DB. I would like to be able to retrieve the connection string from my AppSettings.json file in the DB Context. I believe the correct place to do that would be within the OnConfiguring()
method.
Is that correct?
Given this model, how do I correctly access the AppSettings.json file in the DBContext class?