Reputation: 10932
How do I go about caching objects that implement the IDisposable interface using the CacheManager from the Microsoft Enterprise Library?
When an object expires, Dispose() is never called for that object and I can't override Remove(...) either.
Upvotes: 2
Views: 490
Reputation: 22655
It's not entirely clear to me that it should be the cache's responsibility to call Dispose; just because an item is removed from the cache does not mean that it is not being referenced elsewhere.
Also, if an object implements the IDisposable pattern then the Finalizer should call Dispose (if Dispose has not already been called).
However, Enterprise Library does give you a hook to allow you to perform any actions you deem necessary. The interface is the ICacheItemRefreshAction interface. When an item is removed from the cache the ICacheItemRefreshAction.Refresh method will be invoked on a separate thread.
When an item is added to the cache the ICacheItemRefreshAction can be specified.
An example of its usage:
[Serializable]
public class DisposeRefreshAction : ICacheItemRefreshAction
{
public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
{
// Item has been removed from cache. Perform desired actions here, based on
// the removal reason (for example, refresh the cache with the item).
if (expiredValue != null && expiredValue is IDisposable)
{
((IDisposable)expiredValue).Dispose();
}
}
}
public class MyClass : IDisposable
{
public void Dispose()
{
Console.WriteLine("Dispose!");
}
}
var cache = EnterpriseLibraryContainer.Current.GetInstance<CacheManager>("Cache Manager");
cache.Add("myKey", new MyClass(), CacheItemPriority.Normal,
new DisposeRefreshAction(), new SlidingTime(TimeSpan.FromSeconds(2)));
Upvotes: 2