Aiursoft.InMemoryKvDb 1.0.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package Aiursoft.InMemoryKvDb --version 1.0.3
                    
NuGet\Install-Package Aiursoft.InMemoryKvDb -Version 1.0.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Aiursoft.InMemoryKvDb" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Aiursoft.InMemoryKvDb" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="Aiursoft.InMemoryKvDb" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Aiursoft.InMemoryKvDb --version 1.0.3
                    
#r "nuget: Aiursoft.InMemoryKvDb, 1.0.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Aiursoft.InMemoryKvDb&version=1.0.3
                    
Install Aiursoft.InMemoryKvDb as a Cake Addin
#tool nuget:?package=Aiursoft.InMemoryKvDb&version=1.0.3
                    
Install Aiursoft.InMemoryKvDb as a Cake Tool

Aiursoft InMemoryKvDb

MIT licensed Pipeline stat Test Coverage NuGet version (Aiursoft.InMemoryKvDb) ManHours

Aiursoft InMemoryKvDb is a lightweight, thread-safe, in-memory key-value database with support for automatic Least Recently Used (LRU) cache eviction. It allows for efficient storage and retrieval of key-value pairs while preventing unbounded memory usage by leveraging configurable LRU eviction policies.

This library is ideal for scenarios where you need an in-memory cache that automatically discards the least recently accessed items, such as storing temporary user data, caching API responses, or handling in-memory operations for temporary data processing, without worrying about potential memory overflows.

Why this project

The traditional way to create an In-Memory Key-Value Database in C# is:

public class InMemoryDatabase : ISingletonDependency
{
    private ConcurrentDictionary<Guid, Player> Players { get; } = new();
    
    public Player GetOrAddPlayer(Guid id)
    {
        lock (Players)
        {
            return Players.GetOrAdd(id, _ => new Player(id)
            {
                NickName = "Anonymous " + new Random().Next(1000, 9999)
            });
        }
    }
    
}

However, if a hacker keeps calling GetOrAddPlayer with a new Guid, the Players dictionary will grow infinitely. And cause you OutOfMemoryException.

Installation

First, install Aiursoft.InMemoryKvDb to your ASP.NET Core project from nuget.org:

dotnet add package Aiursoft.InMemoryKvDb

Add the service to your IServiceCollection in Startup.cs (or Program.cs in .NET 6 and later):

1. Registering the Service

In your ASP.NET Core application, register the LruMemoryStore service with your desired configuration in Startup.cs (or Program.cs for .NET 6+):

public class Player
{
    public Guid Id { get; set; }
    public string NickName { get; set; }
    
    public Player(Guid id)
    {
        Id = id;
    }
}

services.AddNamedLruMemoryStore<Player>(
    id => new Player(id) { NickName = "Anonymous " + new Random().Next(1000, 9999) },
    maxCachedItemsCount: 4096);

This configuration sets up a store with a maximum of 4096 cached items and uses a custom initialization function to generate a Player instance when a key is not found.

2. Accessing the Store

To use a specific named store, retrieve an instance of NamedLruMemoryStoreProvider<T> and access the desired named store:

var namedProvider = serviceProvider.GetRequiredService<NamedLruMemoryStoreProvider<Player>>();
var normalPlayerDb = namedProvider.GetStore("NormalPlayerDb");
var highLevelPlayerDb = namedProvider.GetStore("HighLevelPlayerDb");

// Retrieve or add a player to the normal player database
var playerId = Guid.NewGuid();
var player = normalPlayerDb.GetOrAdd(playerId);
3. LRU Eviction in Action

The LruMemoryStore automatically manages the eviction of least recently used items when the maximum capacity is reached. You can set different capacities for different named stores as needed.

Configuration Options

  • maxCachedItemsCount: The maximum number of items allowed in the store before eviction starts. Default is 4096.

Example Scenario

Consider a multiplayer game where player data is cached in memory for fast access. Using Aiursoft.InMemoryKvDb, you can efficiently cache player profiles while automatically managing memory usage:

services.AddNamedLruMemoryStore<Player>(
    id => new Player(id) { NickName = "Guest" + new Random().Next(1000, 9999) },
    maxCachedItemsCount: 2048);

By using AddNamedLruMemoryStore, you ensure that memory usage remains bounded, reducing the risk of OutOfMemoryException from uncontrolled cache growth.

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any feature requests, bug fixes, or other improvements.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Aiursoft.InMemoryKvDb:

Repository Stars
AiursoftWeb/Kahla
Kahla is a cross-platform business messaging app. Mirror of https://gitlab.aiursoft.cn/aiursoft/kahla
Version Downloads Last updated
9.0.4 168 4/9/2025
9.0.3 209 3/12/2025
9.0.2 162 2/12/2025
9.0.1 124 1/15/2025
9.0.0 116 1/2/2025
1.0.7 115 1/1/2025
1.0.6 232 11/11/2024
1.0.5 108 11/11/2024
1.0.4 104 11/11/2024
1.0.3 109 11/11/2024
1.0.2 101 11/11/2024
1.0.1 103 11/11/2024