Connect to SQLite
Цей контент ще не доступний вашою мовою.
This page describes how consuming apps connect to a SQLite resource that’s already modeled in your AppHost. For the AppHost API surface — adding a SQLite resource, setting a custom database file path, the SQLiteWeb UI, SQLite extensions, and more — see SQLite Hosting integration.
When you reference a SQLite resource from your AppHost, Aspire injects the database file path into the consuming app as an environment variable. Your app can either read that environment variable directly — the pattern works the same from any language — or, in C#, use the Aspire SQLite client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the DataSource property of a resource called sqlite becomes SQLITE_DATASOURCE.
The SQLite resource exposes the following connection property:
| Property Name | Description |
|---|---|
DataSource | The file-system path to the SQLite database file |
Example value:
DataSource: C:\Users\username\AppData\Local\Temp\sqlite.dbConnect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds a SQLite resource named sqlite and references it from the consuming app.
For C# apps, the recommended approach is the Aspire SQLite client integration (from the .NET Aspire Community Toolkit). It registers a SqliteConnection through dependency injection and adds health checks and telemetry automatically. If you’d rather read the environment variable directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 CommunityToolkit.Aspire.Microsoft.Data.Sqlite NuGet package in the client-consuming project:
dotnet add package CommunityToolkit.Aspire.Microsoft.Data.Sqlite#:package CommunityToolkit.Aspire.Microsoft.Data.Sqlite@*<PackageReference Include="CommunityToolkit.Aspire.Microsoft.Data.Sqlite" Version="*" />Add the SQLite connection
Section titled “Add the SQLite connection”In Program.cs, call AddSqliteConnection on your IHostApplicationBuilder to register a SqliteConnection:
builder.AddSqliteConnection(connectionName: "sqlite");Resolve the connection through dependency injection:
public class ExampleService(SqliteConnection connection){ // Use connection to query the database...}Add keyed SQLite connections
Section titled “Add keyed SQLite connections”To register multiple SqliteConnection instances with different connection names, use AddKeyedSqliteConnection:
builder.AddKeyedSqliteConnection(name: "chat");builder.AddKeyedSqliteConnection(name: "queue");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("chat")] SqliteConnection chatConnection, [FromKeyedServices("queue")] SqliteConnection queueConnection){ // Use connections...}Configuration
Section titled “Configuration”The Aspire SQLite client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddSqliteConnection:
builder.AddSqliteConnection("sqlite");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "sqlite": "Data Source=C:\\Database\\Location\\my-database.db" }}For more information, see Microsoft.Data.Sqlite connection strings.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads settings from the Aspire:Sqlite:Client key:
{ "Aspire": { "Sqlite": { "Client": { "ConnectionString": "Data Source=C:\\Database\\Location\\my-database.db", "DisableHealthCheck": true } } }}Inline delegates. Pass an Action<SqliteConnectionSettings> to configure settings inline, for example to disable health checks:
builder.AddSqliteConnection( "sqlite", static settings => settings.DisableHealthCheck = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The SQLite client integration adds:
- A health check that attempts to open a connection to the database file when
SqliteConnectionSettings.DisableHealthCheckisfalse. - Integration with the
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire SQLite client integration automatically configures logging, tracing, and metrics through OpenTelemetry. Because SQLite is an embedded database engine, telemetry support is more limited than server-based databases.
Logging uses standard .NET logging mechanisms for database operations.
Tracing emits activities for database operations via OpenTelemetry when configured.
Metrics support is limited compared to server-based database integrations due to the nature of SQLite as an in-process engine.
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected data source path from the environment and open a connection directly:
using Microsoft.Data.Sqlite;
var dataSource = Environment.GetEnvironmentVariable("SQLITE_DATASOURCE");
using var connection = new SqliteConnection($"Data Source={dataSource}");await connection.OpenAsync();
// Use connection to query the database...SQLite libraries for Go typically require CGo. For a pure-Go alternative with no CGo dependency, use modernc.org/sqlite:
go get modernc.org/sqliteRead the injected environment variable and connect:
package main
import ( "database/sql" "fmt" "os" _ "modernc.org/sqlite")
func main() { // Read the Aspire-injected data source path dataSource := os.Getenv("SQLITE_DATASOURCE")
db, err := sql.Open("sqlite", dataSource) if err != nil { panic(err) } defer db.Close()
if err := db.Ping(); err != nil { panic(err) }
fmt.Println("Connected to SQLite:", dataSource) // Use db to query the database...}Python ships with a built-in sqlite3 module — no additional installation is required:
import osimport sqlite3
# Read the Aspire-injected data source pathdata_source = os.getenv("SQLITE_DATASOURCE")
connection = sqlite3.connect(data_source)cursor = connection.cursor()
# Use cursor to query the database...connection.close()Install better-sqlite3, a synchronous SQLite client for Node.js:
npm install better-sqlite3npm install --save-dev @types/better-sqlite3Read the injected environment variable and connect:
import Database from 'better-sqlite3';
// Read the Aspire-injected data source pathconst dataSource = process.env.SQLITE_DATASOURCE!;
const db = new Database(dataSource);
// Use db to query the database...db.close();