Sub topic 14
Using DbContext in ASP.NET Core with Dependency Injection
In earlier chapters you created a context yourself with new BloggingContext(). That works in a console app. A web app works differently. It handles many requests, often at the same time, and each request needs its own context. ASP.NET Core has a built-in tool for this called dependency injection. This chapter shows how to use it with EF Core.
What Dependency Injection Means
A dependency is an object your code needs in order to do its job. A DbContext is a dependency of any code that reads or writes data.
Dependency injection (DI) is a pattern where your code does not create its own dependencies. Your code asks for them, and something else hands them over.
In ASP.NET Core, that "something else" is the DI container. It is a built-in object that knows how to build services and when to throw them away. A service is any class you register with the container.
There are three benefits:
- Your code does not need to know the connection string or which provider is used.
- The container creates and disposes the context at the right time.
- In tests, you can hand your code a different context, such as one that points to a test database.
Service Lifetimes
When you register a service, you choose its lifetime. The lifetime controls how long one instance lives.
| Lifetime | One instance per... | Typical use |
|---|---|---|
| Singleton | Whole app, for as long as it runs | Settings, caches |
| Scoped | Web request | `DbContext` |
| Transient | Every time it is requested | Small, stateless helpers |
AddDbContext registers your context as scoped by default. Each HTTP request gets a fresh context. When the request ends, the container disposes the context and closes its connection.
This is the right fit because a DbContext is meant to be short-lived. It tracks the entities it loads, so a long-lived context keeps growing. It is also not thread-safe, meaning two pieces of code must not use one context at the same time.
Setting Up the Web Project
Create a new, empty ASP.NET Core project and add the same packages as before:
dotnet new web -o BlogApi
cd BlogApi
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.DesignIf you have not installed the dotnet-ef tool yet, run dotnet tool install --global dotnet-ef.
Moving the Connection String into Configuration
A connection string tells the provider where the database is. In a web app it belongs in configuration, not in code. That way you can use a different database in production without rebuilding.
Open appsettings.json and add a ConnectionStrings section:
{
"ConnectionStrings": {
"Default": "Data Source=blogging.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}Changing the Context to Accept Options
In earlier chapters, the context set up SQLite in OnConfiguring. With DI, the container passes the settings in instead. The context gets a constructor that takes DbContextOptions<AppDbContext> and passes it to the base class. Options here means the provider and connection string, bundled into one object.
A Complete Program.cs
Replace the contents of Program.cs with this:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Register the context. Its lifetime is scoped: one per request.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("Default")));
// Register our own service that uses the context.
builder.Services.AddScoped<BlogService>();
var app = builder.Build();
// The context is injected straight into the endpoint.
app.MapGet("/blogs", async (AppDbContext db) =>
await db.Blogs.AsNoTracking().ToListAsync());
app.MapGet("/blogs/{id:int}", async (int id, AppDbContext db) =>
await db.Blogs.FindAsync(id) is Blog blog
? Results.Ok(blog)
: Results.NotFound());
// The service is injected, and it receives the context itself.
app.MapPost("/blogs", async (Blog blog, BlogService service) =>
{
var created = await service.CreateAsync(blog.Url);
return Results.Created($"/blogs/{created.BlogId}", created);
});
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>();
}
public class BlogService
{
private readonly AppDbContext _db;
public BlogService(AppDbContext db) => _db = db;
public async Task<Blog> CreateAsync(string url)
{
var blog = new Blog { Url = url };
_db.Blogs.Add(blog);
await _db.SaveChangesAsync();
return blog;
}
}The code shows two ways to get a context:
- Endpoint parameter. The
/blogsGET endpoints listAppDbContext dbas a parameter. ASP.NET Core sees that the type is registered and passes in the request's context. - Constructor injection.
BlogServiceasks forAppDbContextin its constructor. When the POST endpoint asks forBlogService, the container builds it and passes in the same request's context.
Both ways get the same context instance within one request, because the context is scoped.
Creating the Database and Running the App
The dotnet ef tool is smart enough to start your app's host and ask the DI container for the context. So the same commands work:
dotnet ef migrations add InitialCreate
dotnet ef database update
dotnet runThe app prints a URL such as http://localhost:5000. Your port number may be different. In a second terminal, try it:
curl -X POST http://localhost:5000/blogs -H "Content-Type: application/json" -d '{"url":"https://example.com/blog"}'
curl http://localhost:5000/blogsThe first command adds a blog. The second returns a JSON list that contains it.
Common Mistakes
Injecting the context into a singleton
A singleton lives for the whole app. If it holds a scoped context, that one context gets shared by every request. ASP.NET Core checks for this during development and throws an error that says it "cannot consume scoped service".
Using one context from two threads
Starting two queries on the same context without awaiting the first one throws InvalidOperationException. Always await each call before you start the next.
Background work
A background task runs outside any request, so it has no request scope. For that case, register a factory with AddDbContextFactory<AppDbContext>(...). Then inject IDbContextFactory<AppDbContext> and create a short-lived context with await using var db = await factory.CreateDbContextAsync();.
Exercises
Exercise
Why does AddDbContext register the context as scoped instead of singleton?
Show answer
A DbContext is meant to be short-lived and is not thread-safe. Scoped gives each HTTP request its own fresh context, and the container disposes it when the request ends. A singleton would share one context across all requests at the same time, and its change tracker would keep growing.
Exercise
Add a DELETE /blogs/{id} endpoint to Program.cs that removes a blog and returns 204 No Content, or 404 Not Found if no blog has that id.
Show answer
app.MapDelete("/blogs/{id:int}", async (int id, AppDbContext db) => { var blog = await db.Blogs.FindAsync(id); if (blog is null) return Results.NotFound(); db.Blogs.Remove(blog); await db.SaveChangesAsync(); return Results.NoContent(); }); The context is injected as an endpoint parameter, just like in the GET endpoints.
Exercise
You register a class called ReportCache with AddSingleton, and its constructor takes AppDbContext. The app throws an error at startup in development. What is wrong, and what is one fix?
Show answer
A singleton cannot depend on a scoped service, because it would keep one context for the whole app. One fix is to inject IDbContextFactory<AppDbContext> (registered with AddDbContextFactory) and create a new context inside each method that needs one. Another fix is to make ReportCache scoped.