I honestly cannot believe how hard this is...first off the requirements that I am going for:
IDesignTimeDbContex
I am a bit confused with your question. Are you using dependency injection for the DbContext
or are you trying to initialize and construct the context ad hoc?
I am doing what you have described in one of my solutions. Here is my solution structure:
Startup.cs
public Startup(IHostingEnvironment env)
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json")
.AddEnvironmentVariables();
// ...
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext(
options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
sqlOptions => sqlOptions.EnableRetryOnFailure()));
// SQL configuration for non-injected dbcontext
DbContextOptionsBuilder builder = new DbContextOptionsBuilder();
builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
services.AddSingleton(builder.Options);
// ...
}
MyDbContext.cs
public class MyDbContext : IdentityDbContext
{
public MyDbContext(DbContextOptions options) : base(options) { }
}
If you are not using dependency injection to pass the DbContext, you can access the SQL properties by injecting DbContextOptions
instead.
In this example, the appsettings file is only every read once and everything just works.