In webmethods, it is very simple to implement caching by annotating [WebMethod(CacheDuration...] attribute. Can we create something similar for non-webmethods, such as Static methods?
Any help/tip is appreciated. Thanks in advance.
In webmethods, it is very simple to implement caching by annotating [WebMethod(CacheDuration...] attribute. Can we create something similar for non-webmethods, such as Static methods?
Any help/tip is appreciated. Thanks in advance.
There is no built in feature for achieving exactly what you want. You should use Httpruntime.Cache
.
It's not a built in feature but you may achieve something like that using aspect oriented programming (AOP). Caching information using aspects.
In case you're interested Spring.NET provides AOP
If you can't use AOP to get the job done you could try using this little class I put together.
public MyClass CachedInstance
{
get { return _cachedInstance.Value; }
}
private static readonly Cached<MyClass> _cachedInstance = new Cached<MyClass>(() => new MyClass(), TimeSpan.FromMinutes(15));
public sealed class Cached<T>
{
private readonly Func<T> _createValue;
private readonly TimeSpan _cacheFor;
private DateTime _createdAt;
private T _value;
public T Value
{
get
{
if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
{
lock (this)
{
if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
{
_value = _createValue();
_createdAt = DateTime.Now;
}
}
}
return _value;
}
}
public Cached(Func<T> createValue, TimeSpan cacheFor)
{
if (createValue == null)
{
throw new ArgumentNullException("createValue");
}
_createValue = createValue;
_cacheFor = cacheFor;
}
}