[英]How should using statement look when using Dependency Injection for DBContext?
When injecting DBContext into my repository, how should the using
statement look?将 DBContext 注入我的存储库时,
using
语句应该如何显示?
Ex: Startup.cs例如:Startup.cs
services.AddDbContext<VisualDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
VisualDbContext.cs VisualDbContext.cs
public partial class VisualDbContext : DbContext
{
public VisualDbContext(DbContextOptions<VisualDbContext> options) : base(options)
{}
public DbSet<Template> Template { get; set; }
public DbSet<Exercise> Exercise { get; set; }
public DbSet<Symbol> Symbol { get; set; }
}
Repository存储库
public class TemplateRepository : ITemplateRepository
{
private readonly VisualDbContext _dbContext;
public TemplateRepository(VisualDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<KeyValuePair<char, string>>> GetTemplateAsync(int templateId)
{
using (_dbContext) //this seems wrong...
{
...
}
}
In .NET Core's DI, the DbContext will be registered as a Scoped Service , which means that its lifetime is controlled by the DI container, and you don't have to worry about it.在 .NET Core 的 DI 中,DbContext 将注册为Scoped Service ,这意味着它的生命周期由 DI 容器控制,您不必担心它。
In ASP.NET Core the Scope is tied to the Http Request, so you'll get the same DbContext instance injected into all dependent services over the course of the request processing, and the DbContext will be Disposed at the end of the Request.在 ASP.NET Core 中,Scope 与 Http 请求相关联,因此您将在请求处理过程中将相同的 DbContext 实例注入到所有依赖服务中,并且 DbContext 将在请求结束时被处置。
This both simplifies your code, as you can omit the initialization of the DbContext and the using
blocks that are otherwise necessary, and it enables you to easily scope transactions that cross service boundaries.这既简化了您的代码,因为您可以省略 DbContext 的初始化和否则需要的
using
块,并且它使您能够轻松地确定跨越服务边界的事务的范围。
By defining the property _dbContext you shouldn't need to use the using statement.通过定义 _dbContext 属性,您不需要使用 using 语句。 It basically makes a new VisualDbContext while you are using the repository and it will dispose of it when you are finished using the repository.
它基本上会在您使用存储库时创建一个新的 VisualDbContext,并在您使用完存储库后处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.