在ASP.Net Core中每个请求一次创建EF Core上下文

Pie*_*tro 2 c# entity-framework-core asp.net-core

在阅读了大量有关该主题的内容之后,似乎一个好的方法是为每个请求创建一个上下文。

为此,我在Startup.cs中声明了两个静态对象

public class Startup
{
    public static DbContextOptionsBuilder<MCContext> optionsBuilder = new DbContextOptionsBuilder<MCContext>();
    public static MCContext db = null;
Run Code Online (Sandbox Code Playgroud)

然后在应用启动时使用init optionsBuilder初始化(因此只有一次):

public Startup(IConfiguration configuration)
{
    optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
}
Run Code Online (Sandbox Code Playgroud)

而db每次请求时:

app.Use(async (context, next) =>
{
    db = db ?? new MCContext(optionsBuilder.Options);
    await next.Invoke(); 
});
Run Code Online (Sandbox Code Playgroud)

然后,当我需要控制器或剃须刀页面cs中的上下文时,可以使用Startup.db获取它:

User cur = await Startup.db.User.Where(x => x.Id == uid).FirstOrDefaultAsync();
Run Code Online (Sandbox Code Playgroud)

我不按照这里处置上下文

因为我不熟悉DI,所以我想知道这种方法是否正确,或者是否缺少任何东西。

Moh*_*hid 7

基于EF Core 2.0的新增功能-EF Core | 微软文档

如果您希望每个请求一次新的上下文:AddDbContext

public void ConfigureServices(IServiceCollection services)
{
 services.AddDbContext<MCContext >(
     options => options.UseSqlServer(connectionString));
 }
Run Code Online (Sandbox Code Playgroud)

那么你也能

public class TiketsController : ControllerBase
{
    private readonly MCContext _context;

    public TiketsController (MCContext context)
    {
        _context = context;
    }
 }
Run Code Online (Sandbox Code Playgroud)

在ASP.NET Core应用程序中使用EF Core的基本模式通常包括将自定义DbContext类型注册到依赖项注入系统中,然后通过控制器中的构造函数参数获取该类型的实例。这意味着将为每个请求创建一个新的DbContext实例。

但是如果您需要高性能/安全重用:AddDbContextPool

public void ConfigureServices(IServiceCollection services)
{
 services.AddDbContextPool<MCContext >(
     options => options.UseSqlServer(connectionString));
 }
Run Code Online (Sandbox Code Playgroud)

那么你也能

public class TiketsController : ControllerBase
{
    private readonly MCContext _context;

    public TiketsController (MCContext context)
    {
        _context = context;
    }
 }
Run Code Online (Sandbox Code Playgroud)

如果使用此方法,则在控制器请求DbContext实例时,我们将首先检查池中是否有可用的实例。请求处理完成后,实例上的任何状态都将重置,实例本身将返回到池中。