title: Entity Framework Core connection management
body: <p>In an asp.net core project, I need an encrypted SQLite database. For that, I made my own <code>SqliteEncryptedConnection</code> which inherits from <code>Microsoft.Data.Sqlite.SqliteConnection</code> and which sets the encryption key in the <code>Open()</code> method (execute PRAGMA key = ...)</p>
  
  <p>I have an extension method that configures my EF context by creating a connection and giving it.</p>
  
  <pre><code>    public static void UseEncryptedSqlite(this DbContextOptionsBuilder optionsBuilder, string connectionString, string password)
      {
          var connection = new SqliteEncryptedConnection(connectionString, password);
          connection.Open();
          optionsBuilder.UseSqlite(connection);
      }
  </code></pre>
  
  <p>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 <code>Open()</code> method is now quite expensive.</p>
  
  <p>My problem with this solution is that my connection is never disposed nor closed!</p>
  
  <ol>
  <li>Is it correct to set the encryption key in Open?</li>
  <li>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?</li>
  <li>Is there another (better) way to manage the connection?</li>
  </ol>
  
  <p>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.</p>