Dependency Injection - bitfaster/BitFaster.Caching GitHub Wiki

The BitFaster.Caching.DependencyInjection NuGet package enables caches to be registered using Microsoft.Extensions.DependencyInjection.

To install the NuGet package, run:

dotnet add package BitFaster.Caching.DependencyInjection

Then simply register a cache type as part of ASP.NET Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging();
    services.AddAuthentication();
    
    // ...

    // Register a ConcurrentLru<int, string> as an ICache<int, string> singleton, with a capacity of 666
    services.AddLru<int, string>(builder =>
       builder
          .WithCapacity(128)
          .Build());

    // ...
}

This adds an ICache registration where the key is an integer and the cached value is a string, backed by ConcurrentLru. The builder delegate is used to configure the registered cache with a capacity of 666, see the wiki for more details about the builder API and configurable cache features.

Then resolve dependencies at runtime by type, for example via the constructor:

public class FooController : Controller
{
    private readonly ICache<int, string> cache;

    // ICache<int, string> is registered, and will therefore be injected at runtime
    public FooController(ICache<int, string> cache)
    {
       this.cache = cache;
    }
}