CacheDrive 0.1.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package CacheDrive --version 0.1.1                
NuGet\Install-Package CacheDrive -Version 0.1.1                
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="CacheDrive" Version="0.1.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CacheDrive --version 0.1.1                
#r "nuget: CacheDrive, 0.1.1"                
#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.
// Install CacheDrive as a Cake Addin
#addin nuget:?package=CacheDrive&version=0.1.1

// Install CacheDrive as a Cake Tool
#tool nuget:?package=CacheDrive&version=0.1.1                

CacheDrive

Installation

Use NuGet Package Manager

Install-Package CacheDrive

or .NET CLI

dotnet add package CacheDrive

or just copy into the project file to reference the package

<PackageReference Include="CacheDrive" Version="0.1.1" />

How to use

  • Register a CacheDrive library, e.g.
var services = new ServiceCollection();

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

services.RegisterCacheDrive(configuration, configurationSectionName: "CacheSettings");

var serviceProvider = services.BuildServiceProvider();

// rest of the app

serviceProvider.Dispose();
  • Optionally add the configuration in appsettings.json
{
  "CacheSettings": {
    "CacheEnabled": true,
    "CacheFolderName": "cache",
    "CacheExpirationType": "Minutes",
    "CacheExpiration": 60,
    "CacheType": "MemoryAndFile",
    "InitializeOnStartup": true,
    "FlushOnExit": true
  }
}
  • You can also specify configurations when registering the cacheDrive library
services.RegisterCacheDrive(settings: new CacheSettings
{
    CacheEnabled = true,
    CacheFolderName = "cache",
    CacheExpirationType = CacheExpirationType.Minutes,
    CacheExpiration = 60,
    CacheType = CacheType.MemoryAndFile,
    InitializeOnStartup = true,
    FlushOnExit = true
});
  • Then by injecting ICacheService you can start using write and read from the cache
public class App
{
    private readonly ICacheService _cacheService;

    public App(ICacheService cacheService)
    {
        _cacheService = cacheService;
    }

    public async Task Run()
    {
        // SetAsync, GetAsync and TryGetValue
        string cacheKey1 = "testKey";
        await _cacheService.SetAsync(cacheKey1, "test text...");
        var cachedValue1 = await _cacheService.GetAsync<string>(cacheKey1);
        Console.WriteLine($"GetAsync - cached value: {cachedValue1}");
        
        Console.WriteLine(_cacheService.TryGetValue(cacheKey1, out string cachedValue2)
            ? $"TryGetValue OK - cached value: {cachedValue2}"
            : $"TryGetValue NOK - cached value: {cachedValue2}");

        // Set, Get
        string cacheKey2 = "testKey2";
        _cacheService.Set(cacheKey2, 1234567);
        int cachedValue3 = _cacheService.Get<int>(cacheKey2);
        Console.WriteLine($"Get - cached value: {cachedValue3} ");
    }
}

ICacheService API Explanation

public interface ICacheService
{
    /// <summary>
    /// Initializes the cache, such as loading data from a file, database, and so on.
    /// Should be run before the cache is used, usually at application startup.
    /// Can be used many times, each time adding or overwriting data if they have the same keys.
    /// </summary>
    Task InitializeAsync();

    /// <summary>
    /// Dumps cached data into files, database, and so on.
    /// Usually it should be run before the application terminates.
    /// Can be used many times, each time saving data that are new or has been changed.
    /// </summary>
    Task FlushAsync();
    
    /// <summary>
    /// Returns whether an object with the specified key exists in the cache.
    /// </summary>
    /// <param name="key">The key of the value to check.</param>
    /// <returns>true if the key was found in the cache, otherwise, false.</returns>
    bool HasItem(string key);

    /// <summary>
    /// Attempts to get the value associated with the specified key from the cache.
    /// </summary>
    /// <param name="key">The key of the value to get.</param>
    /// <param name="value">
    /// When this method returns, value contains the object from
    /// the cache with the specified key or the default value of
    /// <typeparamref name="T"/>, if the operation failed.
    /// </param>
    /// <returns>true if the key was found in the cache, otherwise, false.</returns>
    bool TryGetValue<T>(string key, out T value);

    /// <summary>
    /// Get the value associated with the specified key from the cache.
    /// </summary>
    /// <param name="key">The key of the value to get.</param>
    /// <returns>The value contains the object from the cache with the specified
    /// key or the default value of T, if the operation failed.
    /// </returns>
    T Get<T>(string key);
    
    /// <summary>
    /// Get the value associated with the specified key from the cache.
    /// </summary>
    /// <param name="key">The key of the value to get.</param>
    /// <returns>The value contains the object from the cache with the specified
    /// key or the default value of T, if the operation failed.
    /// </returns>
    Task<T> GetAsync<T>(string key);

    /// <summary>
    /// Adds a value to the cache if the key does not already exist, or updates if the key already exists.
    /// </summary>
    /// <param name="key">The key to be added or whose value should be updated.</param>
    /// <param name="value">The value to add or update.</param>
    /// <param name="expirySeconds">After how many seconds a given value will expire in the cache. Optional parameter.
    /// By default, the value is taken from the configuration.</param>
    void Set<T>(string key, T value, int expirySeconds = 0);
    
    /// <summary>
    /// Adds a value to the cache if the key does not already exist, or updates if the key already exists.
    /// </summary>
    /// <param name="key">The key to be added or whose value should be updated.</param>
    /// <param name="value">The value to add or update.</param>
    /// <param name="expirySeconds">After how many seconds a given value will expire in the cache. Optional parameter.
    /// By default, the value is taken from the configuration.</param>
    Task SetAsync<T>(string key, T value, int expirySeconds = 0);

    /// <summary>
    /// Deletes the object associated with the given key.
    /// </summary>
    /// <param name="key">The key of the element to be remove.</param>
    /// <returns>true if an object was removed successfully; otherwise, false.</returns>
    bool Delete<T>(string key);
    
    /// <summary>
    /// Deletes the object associated with the given key.
    /// </summary>
    /// <param name="key">The key of the element to be remove.</param>
    /// <returns>true if an object was removed successfully; otherwise, false.</returns>
    Task<bool> DeleteAsync<T>(string key);

    /// <summary>
    /// Returns the number of objects in the cache.
    /// </summary>
    /// <returns>The number of objects in the cache.</returns>
    int CountCachedObjects();

    /// <summary>
    /// Removes all keys and values from the cache
    /// </summary>
    void ClearCache();

    /// <summary>
    /// Removes all expired keys and values from the cache
    /// </summary>
    void ClearExpiredObjects();
}

Configuration

public class CacheSettings
{
    /// <summary>
    /// Determines whether cache is enabled.
    /// Default value is true.
    /// </summary>
    public bool CacheEnabled { get; set; } = true;

    /// <summary>
    /// Cache folder name.
    /// Default value is "cache".
    /// </summary>
    public string CacheFolderName { get; set; } = "cache";

    /// <summary>
    /// In what units do we specify cache expiration.
    /// Default value is Minutes.
    /// </summary>
    public CacheExpirationType CacheExpirationType { get; set; } = CacheExpirationType.Minutes;
    
    /// <summary>
    /// After what time the objects in the cache will expire. Based on CacheExpirationType.
    /// Default value is 60.
    /// </summary>
    public int CacheExpiration { get; set; } = 60;

    /// <summary>
    /// Method of storing the cache.
    /// Memory - only in memory.
    /// MemoryAndFile - In memory while the application is running and in files after the application is closed.
    /// Default value is Memory.
    /// </summary>
    public CacheType CacheType { get; set; } = CacheType.Memory;

    /// <summary>
    /// Initialize cache automatically on startup.
    /// Default value is true.
    /// </summary>
    public bool InitializeOnStartup { get; set; } = true;
    
    /// <summary>
    /// Before exit, flush the cache data to a files if necessary.
    /// Default value is true.
    /// </summary>
    public bool FlushOnExit { get; set; } = true;
}
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CacheDrive:

Package Downloads
JK.IpGeolocation

IP Geolocation API based on ipapi.co

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.2.4 264 9/5/2024
0.2.3 91 9/4/2024
0.2.2 92 9/4/2024
0.2.1 91 9/4/2024
0.2.0 187 5/9/2024
0.1.2 156 3/16/2024
0.1.1 372 12/11/2023
0.1.0 146 12/8/2023

Bug fix related to the ability to enable and disable the cache (CacheEnabled).