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

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

Question

Just for testing, I don't want to do dependency injection from StartUp.cs file. How can I get IHostingEnvironment from EF Core DBContext.

I take a new asp.net core project with empty template. I have created a dbcontext as below. I want to user Environment.ContentRootPath instead of Directory.GetCurrentDirectory(). But I don't want to do any injection from Startup.cs.

public class MyDBContext: DbContext
{

    public IConfigurationRoot Configuration { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var builder = new ConfigurationBuilder()
              .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\.."))
              .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; }
}

If I add IHostingEnvironment in dbcontext constructor as below,

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(this.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; }
}

I got following error when I Add-Migration from Package-Manager console.

PM> Add-Migration InitMyDBContext

No parameterless constructor was found on 'MyDBContext'. Either add a parameterless constructor to 'MyDBContext' or add an implementation of 'IDbContextFactory' in the same assembly as 'MyDBContext'.

1
0
1/2/2017 4:56:33 AM

Popular Answer

You should be able to inject the IHostingEnvironment directly into your DbContext's constructor.

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 framework is already aware of the interface.

You add the context as usual. Minus configuration, as you indicated that you don't want to do it in Startup

services.AddDbContext<MyDBContext>();

when initializing the context the framework should inject an implementation of IHostingEnvironment into the context based on the presence of the constructor argument.

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