If you want to use SessionState, you can create your own wrapper so that you can cache the wrapper instead of caching the actual item. The following is a brief, unverified shell example that checks if an element is null, or if it has expired, it will call Func, which you can provide to the updated element.
Func accepts the last set value, so if you can determine if the value really remains valid, you can avoid reloading it.
public class TimeExpirationItem<T> { private T _item=default(T); private TimeSpan _expirationDuration; private Func<T> _getItemFunc; private DateTime _expiresTime; public TimeExpirationItem(TimeSpan expirationDuration, Func<T, T> getItemFunc) { this._getItemFunc = getItemFunc; this._expirationDuration = expirationDuration; } public T Item { get { if (_item == null || ItemIsExpired()) { _item = _getItemFunc(_item); _expiresTime = DateTime.Now.Add(_expirationDuration); } return _item; } } public bool ItemIsExpired() { return DateTime.Now > _expiresTime; } }
Again, this code is provided without warranty and not verified, but is an example of what you can do.
Using this would look something like this:
Session.Add("ObjectKey",new TimeExpirationItem<MyObject>(new TimeSpan(0,0,5),mo=>MyObjectRepository.GetItemByLogin(Request.User.Identity.Name));
source share