且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Asp.Net Core中的DBContext文件中的appsettings.json中读取连接字符串?

更新时间:2023-02-17 08:46:44

您可以在启动文件中设置数据库上下文,而完全不覆盖 OnConfiguring .只需在DbContext类中添加采用 DbContextOptions< TContext> 的构造函数即可.此构造函数应将参数传递给 base 类的构造函数,然后在 Startup.Configure 中调用 AddDbContext< TContext> ,如下所示:

You can setup your db context in the startup file and not override OnConfiguring at all. Just add a constructor that takes DbContextOptions<TContext> to your DbContext class. This constructor should pass on the parameter to the base class' constructor, then call AddDbContext<TContext> in your Startup.Configure as follows:

// your TestContext showing constructor
public class TestContext : DbContext
{
    public TestContext(DbContextOptions<TestContext> options) : base(options){ }
}

// Then in Startup.cs
public class Startup
{
   public IConfiguration Configuration {get;}

   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
       services.AddDbContext<TeamsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("connection_string")));
   }
}

值得注意的是, AddDbContext< TContext> 方法具有重载功能,允许您根据需要将上下文的服务寿命设置为Singleton或Transient.默认值为作用域".

Worth noting is that the AddDbContext<TContext> method has overloads that allow setting the service lifetime for the context to Singleton or Transient if you so wish. The default is Scoped.