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

Viewed 902

When injecting DBContext into my repository, how should the using statement look?

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

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

2 Answers

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.

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.

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.

By defining the property _dbContext you shouldn't need to use the using statement. 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.

Related