Register a DbContext in the DI container to interact with a SQLite database using Entity Framework Core.
- A
DbContext - A SQLite database
Install the Aspire EF Core Sqlite library using the following command:
dotnet add package CommunityToolkit.Aspire.Microsoft.EntityFrameworkCore.Sqlite
In the Program.cs file of your project, call the AddSqliteDbContext<TDbContext> extension method to register the TDbContext implementation in the DI container. This method takes the connection name as a parameter:
builder.AddSqliteDbContext<BloggingContext>("sqlite");For ASP.NET Core applications, you can use the simplified EnrichSqliteDatabaseDbContext<TDbContext> extension method:
// Basic usage with default connection string name "DefaultConnection"
builder.EnrichSqliteDatabaseDbContext<BloggingContext>();
// With custom connection string name
builder.EnrichSqliteDatabaseDbContext<BloggingContext>("MyConnection");
// Disable OpenTelemetry instrumentation
builder.EnrichSqliteDatabaseDbContext<BloggingContext>(enableOpenTelemetry: false);The EnrichSqliteDatabaseDbContext method provides:
- Simplified API: Works directly with
WebApplicationBuilder - Default connection string: Uses "DefaultConnection" by default
- OpenTelemetry integration: Automatically adds EF Core instrumentation for distributed tracing
- Parameter validation: Proper error handling for missing connection strings
Then, in your service, inject TDbContext and use it to interact with the database:
public class MyService(BloggingContext context)
{
// ...
}