In an asp.net core project, I need an encrypted SQLite database. For that, I made my own SqliteEncryptedConnection
which inherits from Microsoft.Data.Sqlite.SqliteConnection
and which sets the encryption key in the Open()
method (execute PRAGMA key = ...)
I have an extension method that configures my EF context by creating a connection and giving it.
public static void UseEncryptedSqlite(this DbContextOptionsBuilder optionsBuilder, string connectionString, string password)
{
var connection = new SqliteEncryptedConnection(connectionString, password);
connection.Open();
optionsBuilder.UseSqlite(connection);
}
I must open the connection before I give it to EF, otherwise it is automatically opened and closed by EF for each single query, and the Open()
method is now quite expensive.
My problem with this solution is that my connection is never disposed nor closed!
The dirty solution would be to dispose the connection in the EF context's Dispose method, but I don't really want to dispose a dependency that was injected and not owned by the context.
I had an answer from Brice Lambson who works in the EF core team:
You're going in the right direction--open connections less. Remember, SQLite connections are essentially just file streams, so keeping them open longer isn't really an issue.
If there's only ever one DbContext instance per connection, the DbContext can still own the connection even if it's created externally. Just dispose the connection inside of DbContext.Dispose().
If that's not enough, you could try creating a connection pool. Managing the lifetime might get tricky. The important thing is that a connection doesn't get used outside of the thread it was created on.
Using Cache=Shared (i.e. Shared-Cache Mode) might also help throughput.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With