扩展企业库缓存块 - 如何获取MyCacheManager的实例?

时间:2009-07-01 14:54:47

标签: caching enterprise-library extending

由于CacheManager的默认实现不提供GetItemsOfType<> (以及许多其他人)我想要建立自己的:

[ConfigurationElementType(typeof(CustomCacheManagerData))]
public class MyCacheManager : ICacheManager
{
    //The same constructor as in CacheAppBlock - CacheManager, but it's public here:
    public MyCacheManager(Cache realCache, BackgroundScheduler scheduler, ExpirationPollTimer pollTimer)
    {
       this.realCache = realCache;
       this.scheduler = scheduler;
       this.pollTimer = pollTimer;
    }
    //the other code is basically copy/paste from CacheManager in EntLib, with some of my methods like:
    public T[] GetItemsOfType<T>()
    {
        return realCache.CurrentCacheState.Values.OfType<T>().ToArray();
    }
    //I also have some other custom code on the underlying Hashtable in realCache
}

cofiguration部分(类型部分指向我的类,不使用加密):

<cachingConfiguration defaultCacheManager="SomeCacheManager">
    <cacheManagers>
      <add expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000"
        numberToRemoveWhenScavenging="10" backingStoreName="Null Storage"
        type="MyNamespace.MyCacheManager, MyNamespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="SomeCacheManager" />
</cacheManagers>
    <backingStores>
      <add encryptionProviderName="" type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Null Storage" />
    </backingStores>
  </cachingConfiguration>

我现在面临的问题是如何创建MyCacheManager? 的:

mCityCacheManager = (MyCacheManager)CacheFactory.GetCacheManager("SomeCacheManager");

抛出异常,说MyCacheManager中没有构造函数(但是,与EntLib的CacheManager相同,只有它们在我的类中公开...)

1 个答案:

答案 0 :(得分:2)

那是因为MyCacheManager与EntLib不完全相同!我并不是指额外的方法。看一下声明。

原始CacheManager:

[ConfigurationElementType(typeof(CacheManagerData))]
public class CacheManager : IDisposable, ICacheManager

MyCacheManager:

[ConfigurationElementType(typeof(CustomCacheManagerData))]
public class MyCacheManager : ICacheManager

除了名称差异(并且您没有扩展IDisposable),请注意元素类型属性。

您正在使用(必须)自定义的。自定义的需要一个构造函数,它将NameValueCollection作为参数。

public MyCacheManager(NameValueCollection collection)

它是一个通用的配置驱动程序,可以这么说,因此不能指望使用包含Cache对象,调度程序和轮询计时器的3参数构造函数来创建实例。相反,它通过基本的NameValueCollection传递这些值(或者您在配置文件中设置的任何内容),您必须手动解析它。

另见:
http://bloggingabout.net/blogs/dennis/archive/2009/10/22/create-a-custom-caching-manager-for-enterprise-library-4.aspx