对 DBContext 使用依赖注入时,using 语句应该如何看待?

How should using statement look when using Dependency Injection for DBContext?

将 DBContext 注入我的存储库时,using 语句应该如何显示?

例如: Startup.cs

services.AddDbContext<VisualDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

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; }
    }

存储库

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...
                {
                   ...
                }
        }

在.NET Core的DI中,DbContext会被注册为一个Scoped Service,也就是说它的生命周期由DI容器控制,你不用担心[=12] =]

在 ASP.NET Core 中,Scope 与 Http Request 相关联,因此您将在请求处理过程中将相同的 DbContext 实例注入到所有相关服务中,并且 DbContext 将在请求结束。

这既简化了您的代码,因为您可以省略 DbContext 和 using 块的初始化,否则这些是必需的,并且它使您能够轻松地确定跨越服务边界的事务范围。

通过定义 属性 _dbContext,您不需要使用 using 语句。它基本上会在您使用存储库时创建一个新的 VisualDbContext,并在您使用完存储库后将其丢弃。