SQLite is commonly used in .NET applications that need reliable local storage without running a separate database server. Desktop applications, command-line tools, background services, and offline-first applications often use SQLite because it is simple to deploy and does not require a database server installation.
As an application grows, database access becomes more frequent. Different services may read and update records, background workers may synchronize information, and multiple components may access the same database file. At this stage, how the application manages database connections becomes important.
Some developers create one SQLite connection when the application starts and keep it open until the application closes. Others create a new connection for every database operation but do not dispose of it consistently. Both approaches can introduce problems when the application handles concurrent operations or runs for long periods.
Microsoft.Data.Sqlite provides connection pooling to make connection management more efficient. However, pooling does not mean that developers can ignore connection ownership, transaction boundaries, or resource cleanup.
This article explains how SQLite connections work in .NET, how connection pooling helps, and how to organize database access in a maintainable application.
Understanding the SQLite Connection Lifecycle
A database connection represents an active interaction between a .NET application and an SQLite database.
With Microsoft.Data.Sqlite, the typical lifecycle contains four steps:
- Create a SqliteConnection using a connection string.
- Open the connection.
- Execute commands and complete any required transactions.
- Dispose of the connection after the operation finishes.
A simple implementation looks like this:
using Microsoft.Data.Sqlite;
public static void ReadTasks(string connectionString)
{
using var connection =
new SqliteConnection(connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText =
"SELECT Id, Title FROM Tasks;";
using var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(
$"{reader.GetInt32(0)} - {reader.GetString(1)}");
}
}
The using statements ensure that the connection, command, and reader are disposed of when the method finishes, including when an exception occurs.
This is important because an open connection can hold database resources and participate in locking behavior. A reader that remains open may also keep a statement active longer than expected.
A good general rule is to open a connection shortly before it is needed and dispose of it as soon as the database operation is complete.
Understanding Connection Pooling in Microsoft.Data.Sqlite
Creating and disposing of a connection object for every operation may appear expensive. Connection pooling addresses this concern by allowing the provider to reuse underlying SQLite connections.
When pooling is enabled, disposing of a logical connection generally returns its underlying connection to the pool instead of immediately destroying it. A later connection using the same pooling configuration may reuse that underlying connection.
Pooling is enabled by default in Microsoft.Data.Sqlite versions that support it. It was introduced in version 6.0.
A connection string can explicitly enable pooling:
var connectionString =
"Data Source=app.db;Pooling=True";
Pooling can also be disabled:
var connectionString =
"Data Source=app.db;Pooling=False";
Disabling pooling may be useful for specific diagnostic or resource-management scenarios, but it should not be the default response to ordinary connection problems.
The important distinction is that disposing of a pooled connection still matters. It releases the logical connection so that the provider can make the underlying resource available for reuse.
Creating a Connection Factory
A connection factory provides one place to manage connection creation. Instead of repeating connection-string handling across repositories and services, the application can use a small factory.
using Microsoft.Data.Sqlite;
public sealed class SqliteConnectionFactory
{
private readonly string _connectionString;
public SqliteConnectionFactory(
string connectionString)
{
_connectionString = connectionString;
}
public SqliteConnection CreateConnection()
{
return new SqliteConnection(_connectionString);
}
}
A repository can use the factory whenever it needs database access:
public sealed class TaskRepository
{
private readonly SqliteConnectionFactory _factory;
public TaskRepository(
SqliteConnectionFactory factory)
{
_factory = factory;
}
public List<string> GetTaskTitles()
{
var titles = new List<string>();
using var connection =
_factory.CreateConnection();
connection.Open();
using var command = connection.CreateCommand();
command.CommandText =
"SELECT Title FROM Tasks ORDER BY Id;";
using var reader = command.ExecuteReader();
while (reader.Read())
{
titles.Add(reader.GetString(0));
}
return titles;
}
}
The factory owns the connection configuration, while the repository owns the connection it creates. This separation makes the code easier to test and maintain.
The factory should not return one shared connection instance. It should create a new logical connection for each independent operation and allow pooling to handle reuse.
Using Connection Pooling With Dependency Injection
Applications that use Microsoft.Extensions.DependencyInjection can register the connection factory as a singleton.
The factory is safe to share because it contains an immutable connection string and creates a new connection whenever requested.
var connectionString =
"Data Source=app.db;Pooling=True";
services.AddSingleton(
new SqliteConnectionFactory(connectionString));
services.AddScoped<TaskRepository>();
The repository can then receive the factory through constructor injection.
Avoid registering an already-open SqliteConnection as a singleton:
// Avoid sharing one open connection across the application.
services.AddSingleton<SqliteConnection>(
new SqliteConnection(connectionString));
A singleton connection may be accessed by multiple services at the same time. Microsoft.Data.Sqlite objects such as SqliteConnection, SqliteCommand, and SqliteDataReader are not thread-safe for concurrent use.
Separate logical connections are a better choice for independent operations.
Keeping the Connection String Consistent
Connection pooling depends on the connection configuration. Applications should create and reuse a consistent connection string rather than generating slightly different strings for every operation.
For example, these strings describe similar database configurations:
var first =
"Data Source=app.db;Pooling=True";
var second =
"Pooling=True;Data Source=app.db";
Although the settings are equivalent, relying on differently formatted connection strings can make pool behavior harder to reason about.
Use SqliteConnectionStringBuilder to create the connection string in one place:
var builder = new SqliteConnectionStringBuilder
{
DataSource = "app.db",
Pooling = true,
DefaultTimeout = 30
};
string connectionString = builder.ToString();
The builder also makes it easier to change database settings without manually constructing strings throughout the application.
Avoid adding request identifiers, temporary values, or unnecessary connection options to the connection string. Keep the configuration stable for the lifetime of the application.
Managing Connections in Asynchronous Methods
Microsoft.Data.Sqlite provides asynchronous method signatures such as OpenAsync, ExecuteReaderAsync, and ExecuteNonQueryAsync.
A repository can use these methods with cancellation support:
public async Task<List<string>> GetTaskTitlesAsync(
CancellationToken cancellationToken)
{
var titles = new List<string>();
await using var connection =
_factory.CreateConnection();
await connection.OpenAsync(cancellationToken);
await using var command = connection.CreateCommand();
command.CommandText =
"SELECT Title FROM Tasks ORDER BY Id;";
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
titles.Add(reader.GetString(0));
}
return titles;
}
The await using statements ensure that asynchronous disposal is performed where supported.
There is an important implementation detail to understand: Microsoft.Data.Sqlite's asynchronous ADO.NET methods execute synchronously because SQLite is an embedded database engine rather than a network database client. The asynchronous APIs are provided for compatibility with common .NET data-access patterns, but they do not make SQLite file operations genuinely non-blocking.
For an application that performs substantial database work, consider where the work runs. In a desktop application, long-running database operations should not block the UI thread. A background worker or an appropriate task scheduling strategy can help keep the interface responsive.
Cancellation tokens should also be passed through the application so operations can stop when their caller no longer needs the result. Do not assume that cancellation can interrupt every native SQLite operation immediately.
Managing Transactions and Connection Ownership
A transaction belongs to the connection that created it. Every command participating in that transaction must use the same connection and transaction.
Consider a service that creates an order and its order items. Both operations must succeed together.
public void CreateOrder(
string connectionString,
string customerName,
string productName)
{
using var connection =
new SqliteConnection(connectionString);
connection.Open();
using var transaction =
connection.BeginTransaction();
try
{
using var orderCommand =
connection.CreateCommand();
orderCommand.Transaction = transaction;
orderCommand.CommandText =
"""
INSERT INTO Orders (CustomerName)
VALUES ($customerName);
SELECT last_insert_rowid();
""";
orderCommand.Parameters.AddWithValue(
"$customerName",
customerName);
long orderId =
Convert.ToInt64(orderCommand.ExecuteScalar());
using var itemCommand =
connection.CreateCommand();
itemCommand.Transaction = transaction;
itemCommand.CommandText =
"""
INSERT INTO OrderItems (OrderId, ProductName)
VALUES ($orderId, $productName);
""";
itemCommand.Parameters.AddWithValue(
"$orderId",
orderId);
itemCommand.Parameters.AddWithValue(
"$productName",
productName);
itemCommand.ExecuteNonQuery();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
The transaction ensures that the order and its item are saved as one unit of work.
The connection should remain open until the transaction has completed. Do not create a second connection for a command that must participate in the existing transaction.
Also avoid holding a transaction open while performing network calls, waiting for user input, or processing unrelated data. Long-running transactions can increase database contention.
Avoiding Connection Leaks
Connection leaks occur when an application fails to dispose of connections and other database resources.
One common example is opening a connection without a using statement:
public void SaveTask(string title)
{
var connection =
new SqliteConnection(_connectionString);
connection.Open();
// Database operation
}
The method does not close or dispose of the connection. It may eventually be cleaned up by garbage collection, but the application should never rely on that behavior for database resource management.
The corrected implementation is:
public void SaveTask(string title)
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText =
"INSERT INTO Tasks (Title) VALUES ($title);";
command.Parameters.AddWithValue("$title", title);
command.ExecuteNonQuery();
}
The same rule applies to commands, readers, and transactions. Each resource should have a clear owner and a predictable disposal point.
Another common mistake is returning a SqliteDataReader from a repository after disposing of its connection. A reader depends on the connection that created it. If the repository owns the connection, it should normally read the results and return application objects rather than exposing the reader to callers.
Understanding Pooling During Database Maintenance
Connection pooling introduces an additional consideration when an application needs to replace, delete, or move a database file.
Suppose an application creates a backup and then attempts to replace the active database. Even if a repository has disposed of its logical connection, the provider may still retain an underlying connection in the pool.
For maintenance operations that require exclusive access to the database file, the application should coordinate all database users, close active connections, and use the appropriate pooling maintenance operations supported by its Microsoft.Data.Sqlite version.
Microsoft.Data.Sqlite provides SqliteConnection.ClearPool and SqliteConnection.ClearAllPools for clearing pooled connections. These should be used deliberately when the application has a specific reason to clear the relevant pool, not as a routine operation after every query.
A database replacement workflow should also account for WAL files, active transactions, and other processes that may still be accessing the database. Clearing a pool in one process does not close connections owned by other processes.
For normal repository operations, simply disposing of each logical connection is the preferred approach.
Common Connection Management Mistakes
Several connection-management mistakes appear frequently in SQLite-based applications.
| Mistake | Possible result | Better approach |
|---|
| Sharing one connection across threads | Unsafe concurrent access | Create separate connections |
| Keeping a connection open for the entire application lifetime | Long-lived resources and complicated ownership | Open connections for individual operations |
| Not disposing commands or readers | Resources remain active longer than needed | Use using or await using |
| Creating different connection strings throughout the application | Harder-to-manage pooling configuration | Use one connection factory |
| Opening a second connection inside an existing transaction | Operations do not share the same transaction | Pass the existing connection and transaction |
| Clearing pools after every query | Unnecessary connection recreation | Let normal disposal and pooling work |
A reliable connection strategy should make ownership obvious. The component that creates a connection should normally be responsible for disposing of it.
Best Practices for Production Applications
For a maintainable SQLite implementation, follow these practices:
- Create a new logical connection for each independent database operation.
- Dispose of connections, commands, readers, and transactions consistently.
- Use connection pooling unless a specific requirement justifies disabling it.
- Keep the connection string centralized and consistent.
- Register a connection factory rather than a shared open connection in dependency injection.
- Keep transactions short and limited to related database operations.
- Do not share Microsoft.Data.Sqlite connection objects across concurrent threads.
- Use cancellation tokens in asynchronous application workflows.
- Coordinate database maintenance with all active connections and processes.
- Test connection handling under concurrent access and application shutdown scenarios.
For applications that perform frequent writes, combine good connection management with WAL mode and appropriate transaction design. Connection pooling improves resource reuse, but it does not remove SQLite's single-writer limitation.
Summary
Connection lifecycle management is an important part of building reliable SQLite-based .NET applications. Connections should be created when needed, used for a clearly defined operation, and disposed of as soon as that operation finishes.
Microsoft.Data.Sqlite connection pooling makes this approach efficient by allowing underlying connections to be reused. Developers do not need to keep one connection open globally to avoid connection creation overhead.
A connection factory provides a simple way to centralize configuration and create independent connections. Combined with proper transaction ownership, resource disposal, and consistent connection strings, this design keeps database access easier to maintain.
The main goal is to make connection ownership predictable. When every operation manages its own connection and transaction boundaries, the application becomes easier to test, safer under concurrent access, and more reliable during normal operation and database maintenance.
Join the conversation! Your thoughts help the community grow.