[英]How to handle DBContext instancing in Entity Framework Core
來自 Java 環境,我遇到了一些關於可繼承 DBContext 類的問題。 使用 Java EE 我曾經:
現在使用 EF Core,我看到的幾乎所有示例都通過調用默認構造函數來創建 MyDBContext 的實例:
using (var db = new myContext()){...}
這給我提出了幾個問題:
OnConfiguring(...)
來傳遞選項,而是在Startup.cs
使用AddDbContext
作為服務,我該如何調用構造函數? 現在帶有選項的重載構造函數期望在每次調用構造函數時傳遞它們。通常,您需要每個請求范圍的單個實例
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
// use options as you would use them in the .OnConfiguring
options.UseSqlServer("your connectionString");
);
}
如果在服務中使用構造函數注入,ASP.NET 服務提供程序會將 db 上下文解析為構造函數參數。 以這種方式具有數據庫上下文的所有服務將共享相同的實例。
public class ServiceDependentOnContext
{
private readonly ApplicationDbContext dbContext;
public ServiceDependentOnContext(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
}
確保你也為依賴注入配置了你的服務
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer("your connectionString")
);
services.AddScoped<ServiceDependentOnContext>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.