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'.