2009-07-01 39 views
1

由於CacheManager中的默認實現不提供GetItemsOfType <>(和許多其他)我想建設自己的:擴展企業庫緩存塊 - 如何獲取MyCacheManager的實例?

[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部分(型部分點上我的課,加密ISN使用):

<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中只有他們都在我的班公...)

回答

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