timmkrause timmkrause - 7 months ago 101
C# Question

MemoryCache with AbsoluteExpiration stored in an IOC container using .SingleInstance()

I have an abstraction over the

, this instance uses
for its
and is managed by Autofac as follows:

.WithParameter("cacheName", "MyCache");

Theoretically I want the items to expire absolutely (e.g. in 15 minutes).

The problem (question) is, that it's a single instance over all request and no mechanism in place that resets the expiration to 15 minutes in the future again.
So the refresh would only happen a single time, right?

What's the solution for this? Do I need to hook into an event or something...?


My problem was that I need to specify a certain point in time where the cache key expires:

AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(15)

The cache policy was being set in a private readonly field which only gets initialized when creating an instance of MyCache, but this only happens on application startup (IoC container, single instance).

This works for me now:

private CacheItemPolicy CachePolicy => new CacheItemPolicy
    AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(15)

Everytime the cache item policy is accessed, a new DateTimeOffset is calculated.