【问题标题】:How can I get IHostingEnvironment from DbContext in ASP.NET Core如何从 ASP.NET Core 中的 DbContext 获取 IHostingEnvironment
【发布时间】:2017-05-16 05:08:09
【问题描述】:

只是为了测试,我不想从 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'。

【问题讨论】:

  • 提供问题和预期行为的minimal reproducible example,以便得出解决方案。
  • 亲爱的@Nkosi,我更新了我的问题。提前致谢。本题不针对生产问题,仅供学习。
  • 我仍然不清楚你不想从启动时进行任何注入是什么意思?请澄清这一点。您实际上可以将 IHostingEnvironment 直接注入到 dbcontext 的构造函数中。
  • @Nkosi,如何将 IHostingEnvironment 直接注入到 dbcontext 中?
  • 原问题回答正确。应该为迁移错误发布新问题,因为这是一个不同的问题。我在 2.2 中发现要让迁移很好地发挥作用,我必须从找到 Startup 的项目中运行迁移命令,并且我的上下文也驻留在那里。

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

您应该能够将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 的实现注入到上下文中。

【讨论】:

  • 我收到错误“在 'MyDBContext' 上找不到无参数构造函数。要么将无参数构造函数添加到 'MyDBContext',要么在与 'MyDBContext' 相同的程序集中添加 'IDbContextFactory' 的实现。”
  • 亲爱的@Nkosi,是的,我读过那篇文章。读完那篇文章后,我的问题就来了。我想从 dbcontext 类中读取 Environment.ContentRootPath,而不是硬编码连接字符串。
  • IHostingEnvironment 已弃用,将来将被删除。请改用 IHostEnvironment。我希望这对任何人都有帮助
猜你喜欢
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 2017-06-13
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多