Sub topic 14
Using DbContext in ASP.NET Core with Dependency Injection
So far you have created a DbContext yourself with new BloggingContext(). In a web app, it is better to let ASP.NET Core create the context for you. This chapter shows how.
What Dependency Injection Means
Dependency injection (DI) is a way for a framework to create the objects your code needs and hand them to you. You do not call new yourself. You ask for the object, and the framework supplies it.
ASP.NET Core has a built-in service container. The service container is a list of objects the app knows how to build. You add your DbContext to this list once, at startup. You register a service when you add it to the container.
Why a Scoped Lifetime
A lifetime sets how long one object lives. AddDbContext gives the context a scoped lifetime. Scoped means one new context is created for each web request and thrown away when the request ends.
This fits EF Core well. A context is not safe to share between threads. It also keeps tracking every entity it loads, so a context that lives forever would keep growing. With one context per request, each request gets a fresh context and nothing leaks into the next one.
A Worked Example
Create a web project and add the packages:
dotnet new web -o BlogApi
cd BlogApi
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.DesignPut the connection string in appsettings.json. The code will not need to hold it.
{
"ConnectionStrings": {
"Default": "Data Source=blog.db"
}
}Replace Program.cs with this:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("Default")));
var app = builder.Build();
app.MapGet("/blogs", async (AppDbContext db) =>
await db.Blogs.AsNoTracking().ToListAsync());
app.Run();
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Blog> Blogs => Set<Blog>();
}Here is what changed compared with earlier chapters:
- The context has no
OnConfiguringmethod. It now has a constructor, the method that runs when an object is created, and the constructor takesDbContextOptions<AppDbContext>. The provider and connection string come in through that options object. AddDbContextregisters the context and sets up those options.- The endpoint lists
AppDbContext dbas a parameter. ASP.NET Core sees the parameter and passes in the context for this request.
Create the database, then run the app:
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet runOpen /blogs in a browser. You get an empty list, [], until you add rows.
Exercise
Why does the AppDbContext constructor take a DbContextOptions<AppDbContext> parameter instead of overriding OnConfiguring?
Show answer
AddDbContext builds the options from configuration, including the SQLite provider and the connection string, and passes them in through the constructor. The context gets its settings from the app, so the connection string stays out of the context class.
Exercise
Two users call /blogs at the same moment. How many AppDbContext objects are created?
Show answer
Two. The context is scoped, so each request gets its own context, and that context is disposed when its request ends.