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!
- Is it correct to set the encryption key in Open?
- Is there a way to know when the context is disposed? Or to configure it to close and dispose the connection after it is disposed?
- Is there another (better) way to manage the connection?
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.
DbContextOptions
object won't be disposed and will be reused for all instances of EF Core DbContext, since the options is passed to the DbContext when it gets initialized. Since 2.0 preview1, even DbContext instances can be polled for high performance scenarions, see this blog post – Tseng Oct 12 '17 at 16:42OpenConnectionForKey
method of theShardMap
object. – Adrian Pavel Dec 22 '17 at 12:01Dispose
method – sroll Feb 23 '18 at 10:09