Entity Framework Core Interview Question #5
How do you register EF Core DbContext in ASP.NET Core?
EF Core Fundamentals & DbContext Junior Beginner
Quick Interview Answer
The usual approach is to register the context with AddDbContext in Program.cs and configure a database provider and connection string.
Detailed Explanation
The usual approach is to register the context with AddDbContext in Program.cs and configure a database provider and connection string.
AddDbContext registers the context as scoped by default, which aligns well with the unit-of-work nature of an HTTP request.
The connection string should come from configuration and production credentials should be protected using appropriate secret-management practices.
Code Example
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));