Ideal for caching, session management, and more.
- Validate Key: Check if a key exists.
- Add Key: Add a key with an expiration time.
- Validate and Add: Validate if a key exists and add it if not.
- Remove Key: Remove a key.
dotnet add package Soenneker.Validators.ExpiringKey
IExpiringKeyValidator
can be registered within DI, and injected:
public static async Task Main(string[] args)
{
...
builder.Services.AddExpiringKeyValidatorAsSingleton();
}
or it can be initialized manually: new ExpiringKeyValidator()
.
Check if a key is present.
bool Validate(string key)
Add a key with an expiration time.
void Add(string key, int expirationTimeMilliseconds)
Validate a key and add it if it doesn't exist.
bool ValidateAndAdd(string key, int expirationTimeMilliseconds) // true if doesn't exist, false if it does
Remove a key.
void Remove(string key)
var validator = new ExpiringKeyValidator();
validator.Add("key1", 5000); // 5 seconds
var invalid = validator.Validate("key1"); // false, key exists
await Task.Delay(7000); // wait 7 seconds
var validAfterTime = validator.Validate("key1"); // true, key does not exist