The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech Leads28-29 May

Join

NuGet Stats Build Code Coverage

Akavache

Akavache: An Asynchronous Key-Value Store for Native Applications

Akavache is an asynchronous, persistent (i.e., writes to disk) key-value store created for writing desktop and mobile applications in C#, based on SQLite3. Akavache is great for both storing important data (i.e., user settings) as well as cached local data that expires.

What's New in V12

Akavache V12 rewrites the SQLite backend for direct SQLitePCLRaw 3.x access, replacing the sqlite-net-pcl ORM layer entirely. The result is lower per-operation allocations, dedicated worker-thread serialization of all native handle access, and commit coalescing for concurrent writes.

See the Migration Guide: V11 to V12 for upgrade instructions.

Quick Start

1. Install Packages

<PackageReference Include="Akavache.Sqlite3" Version="*" />
<PackageReference Include="Akavache.SystemTextJson" Version="*" />

2. Initialize Akavache

Note: WithAkavache, WithAkavacheCacheDatabase and Initialize always requires an ISerializer defined as a generic type, such as WithAkavache<SystemJsonSerializer>. This ensures the cache instance is properly configured for serialization.

using Akavache.Core;
using Akavache.SystemTextJson;
using Akavache.Sqlite3;
using Splat.Builder;

// Initialize with the builder pattern
AppBuilder.CreateSplatBuilder()
    .WithAkavacheCacheDatabase<SystemJsonSerializer>(builder =>
        builder.WithSqliteProvider() // REQUIRED: Explicitly initialize SQLite provider
               .WithSqliteDefaults(),
            "MyApp");

Important: Always call WithSqliteProvider() explicitly before WithSqliteDefaults(). While WithSqliteDefaults() will automatically call WithSqliteProvider() if not already initialized (for backward compatibility), this automatic behavior is deprecated and may be removed in future versions. Explicit provider initialization is the recommended pattern for forward compatibility with other DI containers.

Dependency Injection Registration (for DI containers)

using Akavache.Core;
using Akavache.SystemTextJson;
using Akavache.Sqlite3;
using Splat.Builder;

// Example: Register Akavache with Splat DI
AppBuilder.CreateSplatBuilder()
    .WithAkavache<SystemJsonSerializer>(
        "MyApp",
        builder => builder.WithSqliteProvider()    // REQUIRED: Explicit provider initialization
                          .WithSqliteDefaults(),
        (splat, instance) => splat.RegisterLazySingleton(() => instance));

// For in-memory cache (testing or lightweight scenarios):
AppBuilder.CreateSplatBuilder()
    .WithAkavache<SystemJsonSerializer>(
        "Akavache",
        builder => builder.WithInMemoryDefaults(),  // No provider needed for in-memory
        (splat, instance) => splat.RegisterLazySingleton(() => instance));

3. Use the Cache

Basic Operations

// Store an object
var user = new User { Name = "John", Email = "john@example.com" };
await CacheDatabase.UserAccount.InsertObject("current_user", user);

// Retrieve an object
var cachedUser = await CacheDatabase.UserAccount.GetObject<User>("current_user");

// Store with expiration
await CacheDatabase.LocalMachine.InsertObject("temp_data", someData, DateTimeOffset.Now.AddHours(1));

// Get or fetch pattern
var data = await CacheDatabase.LocalMachine.GetOrFetchObject("api_data", 
    async () => await httpClient.GetFromJsonAsync<ApiResponse>("https://api.example.com/data"));

Cache Types

Akavache provides four types of caches:

// User preferences (persistent)
await CacheDatabase.UserAccount.InsertObject("user_settings", settings);

// API cache (temporary)
await CacheDatabase.LocalMachine.InsertObject("api_cache", apiData, DateTimeOffset.Now.AddHours(6));

// Sensitive data (encrypted)
await CacheDatabase.Secure.SaveLogin("john.doe", "secretPassword", "myapp.com");

// Session data (in-memory only)
await CacheDatabase.InMemory.InsertObject("current_session", sessionData);

NuGet Packages

Install the packages that match your needs. At minimum you need the core package plus a storage backend and a serializer.

Purpose Package NuGet
Core (in-memory cache) Akavache AkavacheBadge
SQLite persistence Akavache.Sqlite3 Sqlite3Badge
Encrypted SQLite persistence Akavache.EncryptedSqlite3 EncryptedBadge
System.Text.Json serializer (recommended) Akavache.SystemTextJson STJBadge
System.Text.Json BSON serializer Akavache.SystemTextJson.Bson STJBsonBadge
Newtonsoft.Json serializer Akavache.NewtonsoftJson NewtonsoftBadge
HTTP download and caching extensions Akavache.HttpDownloader HttpBadge
Image/bitmap caching Akavache.Drawing DrawingBadge
Application settings helpers Akavache.Settings SettingsBadge
V10 → V11 data migration Akavache.V10toV11 MigrationBadge

Installation

Akavache uses a modular package structure. Choose the packages that match your needs:

Core Package (In Memory only)

<PackageReference Include="Akavache" Version="*" />
<!-- SQLite persistence (most common) -->
<PackageReference Include="Akavache.Sqlite3" Version="*" />

<!-- Encrypted SQLite persistence -->
<PackageReference Include="Akavache.EncryptedSqlite3" Version="*" />

Serializers (Choose One - Required)

<!-- System.Text.Json (fastest, .NET native) -->
<PackageReference Include="Akavache.SystemTextJson" Version="*" />

<!-- Newtonsoft.Json (most compatible) -->
<PackageReference Include="Akavache.NewtonsoftJson" Version="*" />

Optional Extensions

<!-- HTTP download and caching extensions -->
<PackageReference Include="Akavache.HttpDownloader" Version="*" />

<!-- Image/Bitmap support -->
<PackageReference Include="Akavache.Drawing" Version="*" />

<!-- Settings helpers -->
<PackageReference Include="Akavache.Settings" Version="*" />

Framework Support

Akavache supports:

Serializer Compatibility

Serializer .NET Framework 4.6.2+ .NET 8.0+ Mobile Performance
System.Text.Json ✅ Via NuGet Fastest
Newtonsoft.Json ✅ Built-in Compatible

Recommendation: Use System.Text.Json for new projects for best performance. Use Newtonsoft.Json when migrating from older Akavache versions or when you need maximum compatibility.

Akavache.Settings: Configuration Made Easy

Akavache.Settings provides a specialized settings database for application configuration that survives app updates and reinstalls.

Quick Settings Example

using Akavache.Settings;

// 1. Create a settings class — properties are IObservable<T>
public class AppSettings : SettingsBase
{
    public AppSettings() : base(nameof(AppSettings)) { }

    public IObservable<bool> EnableNotifications => GetOrCreateObservable(true);
    public IObservable<Unit> SetEnableNotifications(bool value) => SetObservable(value, nameof(EnableNotifications));

    public IObservable<string> UserName => GetOrCreateObservable("DefaultUser");
    public IObservable<Unit> SetUserName(string value) => SetObservable(value, nameof(UserName));
}

// 2. Initialize with your app
var appSettings = default(AppSettings);

AppBuilder.CreateSplatBuilder()
    .WithAkavache<SystemJsonSerializer>(builder =>
        builder.WithApplicationName("MyApp")
               .WithSqliteProvider()
               .WithSettingsStore<AppSettings>(settings => appSettings = settings));

// 3. Use the settings — subscribe for live updates or read once
await appSettings.SetUserName("John Doe");
await appSettings.SetEnableNotifications(false);

var name = await appSettings.UserName.FirstAsync();
Console.WriteLine($"User: {name}");

Settings are automatically persisted and will survive app updates, making them perfect for user preferences and application configuration.

Documentation

📚 Complete documentation is available in the /docs folder:

Support and Contributing

Thanks

This project is tested with BrowserStack.

We want to thank the following contributors and libraries that help make Akavache possible:

Core Libraries

Microsoft

We thank Microsoft for their ongoing support of the .NET ecosystem and the development tools that make Akavache possible.

License

Akavache is licensed under the MIT License.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.