Skip to content

Instantly share code, notes, and snippets.

@ronaldbarendse
Created December 13, 2023 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronaldbarendse/3367bbacaff4925e0cfa6dbf4aeee83b to your computer and use it in GitHub Desktop.
Save ronaldbarendse/3367bbacaff4925e0cfa6dbf4aeee83b to your computer and use it in GitHub Desktop.
Ensure SQLite in-memory database is persisted for the whole application lifetime.
{
"ConnectionStrings": {
"umbracoDbDSN": "Data Source=Umbraco;Mode=Memory;Cache=Shared;Foreign Keys=True;Pooling=True",
"umbracoDbDSN_ProviderName": "Microsoft.Data.Sqlite"
}
}
using Microsoft.Data.Sqlite;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Composing;
/// <summary>
/// Ensure SQLite in-memory database is persisted for the whole application lifetime.
/// </summary>
internal sealed class SQLiteMemoryComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
string? connectionString = builder.Config.GetUmbracoConnectionString(out var providerName);
if (!string.IsNullOrEmpty(connectionString) &&
Constants.ProviderNames.SQLLite.InvariantEquals(providerName))
{
var connectionStringBuilder = new SqliteConnectionStringBuilder(connectionString);
if (connectionStringBuilder.Mode == SqliteOpenMode.Memory)
{
var connection = new SqliteConnection(connectionString);
connection.Open();
builder.Services.AddHostedService(_ => new SQLiteMemoryHostedService(connection));
}
}
}
/// <summary>
/// Ensure connection is kept open (by keeping a reference) and gets gracefully closed/disposed when application stops.
/// </summary>
private sealed class SQLiteMemoryHostedService : IHostedService, IAsyncDisposable
{
private readonly SqliteConnection _connection;
public SQLiteMemoryHostedService(SqliteConnection connection) => _connection = connection;
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public async Task StopAsync(CancellationToken cancellationToken) => await _connection.CloseAsync();
public async ValueTask DisposeAsync() => await _connection.DisposeAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment