The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextScoped' or 'Singleton' - the first was to fine-grained and the other to coarse. What I required was an instance of the service to have the semantics of 'Singleton' but only for a short time, this is where 'ILifecycle' comes in, it allows you define your own lifecycle for a type inside StrucutreMap.
The soultion I came up with was to use the HttpContext cache to cache the instance of 'IObjectCache' and use the cache timeout - when the item is evicted from the cache we can singal to StructureMap the current life cycle is over and new will be required next time an instance of the service is required.
The soultion I came up with was to use the HttpContext cache to cache the instance of 'IObjectCache' and use the cache timeout - when the item is evicted from the cache we can singal to StructureMap the current life cycle is over and new will be required next time an instance of the service is required.
public class HttpContextCacheLifeStyle : ILifecycle
{
private readonly int _cacheExpirtyInMinutes;
public HttpContextCacheLifeStyle(int cacheExpirtyInMinutes)
{
_cacheExpirtyInMinutes = cacheExpirtyInMinutes;
}
public void EjectAll()
{
FindCache().DisposeAndClear();
}
public IObjectCache FindCache()
{
var objectCache = HttpContext.Current.Cache[Scope
] as IObjectCache;
if (objectCache == null)
{
objectCache = new MainObjectCache();
HttpContext.Current.Cache.Add(Scope
,
objectCache,
null,
DateTime.Now.AddMinutes(_cacheExpirtyInMinutes),
Cache.NoSlidingExpiration,
CacheItemPriority.High, LifeStyleEvicted);
}
return objectCache;
}
private void LifeStyleEvicted(string key, object value, CacheItemRemovedReason reason)
{
((IObjectCache) value).DisposeAndClear();
}
public string Scope
{
get { return GetType().Name; }
}
}
Comments
Post a Comment