仅仅是为了测试,我不想从StartUp.cs文件中进行依赖注入。 如何从EF Core DBContext获取IHostingEnvironment。
我采用一个带有空模板的新asp.net核心项目。我已经创建了一个dbcontext,如下所示。我想用Environment.ContentRootPath而不是Directory.GetCurrentDirectory()。但是我不想从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; }
}
如果我在dbcontext构造函数中添加IHostingEnvironment,如下所示
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; }
}
从Package-Manager控制台添加迁移时出现以下错误。
PM> Add-Migration InitMyDBContext
在'MyDBContext'上找不到无参数构造函数。要么添加一个 无参数构造函数到'MyDBContext'或添加一个实现 'IDbContextFactory'在同一个程序集中 'MyDBContext'。
答案 0 :(得分:2)
您应该能够将IHostingEnvironment
直接注入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; }
}
框架已经知道了界面。
您可以照常添加上下文。减号配置,因为您表示不想在Startup
services.AddDbContext<MyDBContext>();
初始化上下文时,框架应根据构造函数参数的存在将IHostingEnvironment
的实现注入上下文。