Created
December 13, 2023 08:52
-
-
Save ronaldbarendse/3367bbacaff4925e0cfa6dbf4aeee83b to your computer and use it in GitHub Desktop.
Ensure SQLite in-memory database is persisted for the whole application lifetime.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"ConnectionStrings": { | |
"umbracoDbDSN": "Data Source=Umbraco;Mode=Memory;Cache=Shared;Foreign Keys=True;Pooling=True", | |
"umbracoDbDSN_ProviderName": "Microsoft.Data.Sqlite" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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