作者:新人缓冲 | 来源:互联网 | 2022-11-20 19:41
在阅读了大量有关该主题的内容之后,似乎一个好的方法是为每个请求创建一个上下文。
为此,我在Startup.cs中声明了两个静态对象
public class Startup
{
public static DbContextOptionsBuilder optiOnsBuilder= new DbContextOptionsBuilder();
public static MCContext db = null;
然后在应用启动时使用init optionsBuilder初始化(因此只有一次):
public Startup(IConfiguration configuration)
{
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
}
而db每次请求时:
app.Use(async (context, next) =>
{
db = db ?? new MCContext(optionsBuilder.Options);
await next.Invoke();
});
然后,当我需要控制器或剃须刀页面cs中的上下文时,可以使用Startup.db获取它:
User cur = await Startup.db.User.Where(x => x.Id == uid).FirstOrDefaultAsync();
我不按照这里处置上下文
因为我不熟悉DI,所以我想知道这种方法是否正确,或者是否缺少任何东西。
1> Mohamed Elra..:
基于EF Core 2.0的新增功能-EF Core | 微软文档
如果您希望每个请求一次新的上下文:AddDbContext
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(
optiOns=> options.UseSqlServer(connectionString));
}
那么你也能
public class TiketsController : ControllerBase
{
private readonly MCContext _context;
public TiketsController (MCContext context)
{
_cOntext= context;
}
}
在ASP.NET Core应用程序中使用EF Core的基本模式通常包括将自定义DbContext类型注册到依赖项注入系统中,然后通过控制器中的构造函数参数获取该类型的实例。这意味着将为每个请求创建一个新的DbContext实例。
但是如果您需要高性能/安全重用:AddDbContextPool
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool(
optiOns=> options.UseSqlServer(connectionString));
}
那么你也能
public class TiketsController : ControllerBase
{
private readonly MCContext _context;
public TiketsController (MCContext context)
{
_cOntext= context;
}
}
如果使用此方法,则在控制器请求DbContext实例时,我们将首先检查池中是否有可用的实例。请求处理完成后,实例上的任何状态都将重置,实例本身将返回到池中。