How can I get IHostingEnvironment from DbContext in ASP.NET Core

asp.net-core c# entity-framework entity-framework-core

Popular Answer

You need to be able to administer theIHostingEnvironment right into the constructor of your DbContext.

public class MyDBContext: DbContext {
    private readonly IHostingEnvironment env;
    public MyDBContext(IHostingEnvironment env) : base() {
        this.env = env;
    }

    public IConfigurationRoot Configuration { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        Configuration = builder.Build();
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SQLCN"));// @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }

    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Lesson> Lessons { get; set; }
}

The interface is already known to the framework.

As usual, you provide the context. With configuration removed since you said you didn't want to do it inStartup

services.AddDbContext<MyDBContext>();

The framework should inject an implementation of when setting the context toIHostingEnvironment depends on the constructor parameter being present in the context.

2
1/2/2017 4:55:29 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow