A library for strongly-typed caching with DI support (.NET 8).
- Add a reference to the
StrongTypedCache.ExtensionsandStrongTypedCacheLibraryprojects. - Add the
Microsoft.Extensions.DependencyInjectionpackage if you don't have it already.
using Microsoft.Extensions.DependencyInjection;
using StrongTypedCache.Extensions;
var services = new ServiceCollection();
services.AddStrongTypedInMemoryCache<string, MyType>();You can set the expiration time (in seconds):
services.AddStrongTypedInMemoryCache<string, MyType>(absoluteExpirationTimeSec: 600); // 10 minutesCache now supports nullable value types:
// String cache with nullable values
services.AddStrongTypedInMemoryCache<int, string?>();
// Later in code:
cache.CreateEntry(1, null); // ? Allowed!
if (cache.TryGetValue(1, out var value))
{
// value can be null
Console.WriteLine(value?.Length ?? 0);
}using StrongTypedCache.Abstractions;
public class MyService
{
private readonly ICache<string, MyType> _cache;
public MyService(ICache<string, MyType> cache)
{
_cache = cache;
}
public void Example()
{
// Add to cache
_cache.CreateEntry("key1", new MyType());
// Get from cache
if (_cache.TryGetValue("key1", out var value))
{
// use value
}
// Remove from cache
_cache.Remove("key1");
// Get all values
var all = _cache.GetAllValues();
}
}?? Important: Keys cannot be null (enforced by notnull constraint):
// ? This will cause compilation error
services.AddStrongTypedInMemoryCache<string?, MyType>();
// ? Use non-nullable key types
services.AddStrongTypedInMemoryCache<string, MyType>();
services.AddStrongTypedInMemoryCache<int, MyType>();
services.AddStrongTypedInMemoryCache<Guid, MyType>();ICache<TKey, TValue>– main cache interface.InMemoryCache<TKey, TValue>– in-memory implementation.
StrongTypedCache.Abstractions– interfaces.StrongTypedCacheLibrary– cache implementation.StrongTypedCache.Extensions– DI integration.StrongTypedCache.Benchmarks– performance benchmarks using BenchmarkDotNet.
- .NET 8
- Microsoft.Extensions.DependencyInjection
- Microsoft.Extensions.Caching.Memory
MIT