2009-06-24 42 views
29

上下文:.Net 3.5,C#
我想在我的控制檯應用程序中有緩存機制。
而不是重新發明輪子,我想使用System.Web.Caching.Cache(這是一個最終決定,我不能使用其他緩存框架,不要問爲什麼)。
但是,它看起來像System.Web.Caching.Cache應該只在有效的HTTP上下文中運行。我非常簡單的代碼片段看起來是這樣的:如何在控制檯應用程序中使用System.Web.Caching.Cache?

using System; 
using System.Web.Caching; 
using System.Web; 

Cache c = new Cache(); 

try 
{ 
    c.Insert("a", 123); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine("cannot insert to cache, exception:"); 
    Console.WriteLine(ex); 
} 

,其結果是:

 
cannot insert to cache, exception: 
System.NullReferenceException: Object reference not set to an instance of an object. 
    at System.Web.Caching.Cache.Insert(String key, Object value) 
    at MyClass.RunSnippet() 

所以,很顯然,我在這裏做得不對。有任何想法嗎?


更新:+1大部分答案,通過靜態方法獲取緩存是正確的用法,即HttpRuntime.CacheHttpContext.Current.Cache。謝謝你們!

回答

56

Cache構造函數的文檔說它僅供內部使用。要獲取您的Cache對象,請調用HttpRuntime.Cache,而不是通過構造函數創建實例。

9

只要使用Caching Application Block,如果你不想重新發明輪子。如果您仍想使用ASP.NET緩存 - see here。我很確定這隻適用於.NET 2.0及更高版本。這根本是不可能的使用ASP.NET緩存之外的.NET 1

MSDN有緩存文件過多的頁面上一個漂亮的大警告:

Cache類是不旨在用於 以外的ASP.NET應用程序。 它被設計和測試,用於在ASP.NET中爲 應用程序提供緩存。在其他類型的 應用程序,如控制檯 應用程序或Windows窗體 應用程序,ASP.NET緩存可能 無法正常工作。

對於一個非常輕量級的解決方案,您不必擔心過期等問題,那麼字典對象就足夠了。

+0

「看這裏」鏈接被打破 – 2009-06-24 11:52:04

+0

@羅恩 - 這是一個錯誤#1。下面是同一個鏈接的TinyUrl:http://tinyurl.com/ms35eu – RichardOD 2009-06-24 13:20:47

1

嘗試

public class AspnetDataCache : IDataCache 
{ 
    private readonly Cache _cache; 

    public AspnetDataCache(Cache cache) 
    { 
     _cache = cache; 
    } 

    public AspnetDataCache() 
     : this(HttpRuntime.Cache) 
    { 

    } 
    public void Put(string key, object obj, TimeSpan expireNext) 
    { 
     if (key == null || obj == null) 
      return; 
     _cache.Insert(key, obj, null, DateTime.Now.Add(expireNext), TimeSpan.Zero); 
    } 

    public object Get(string key) 
    { 
     return _cache.Get(key); 
    } 

1

的的System.Web.Caching.Cache類依賴於具有其成員 「_cacheInternal」 由的httpRuntime對象設置。

要使用System.Web.Caching類,您必須創建一個HttpRuntime對象並設置HttpRuntime.Cache屬性。你必須有效地模擬IIS。

你最好不要使用其他緩存框架,如:

+1

「通過內部方法設置的唯一方法」 - 不是true,_cacheInternal由靜態屬性訪問器HttpRuntime.Cache設置。然而,我會對更多關於爲什麼MSDN建議ASP.NET緩存不應該用於非web應用的信息感興趣。我有使用它的代碼(它來自此警告存在之前的日期),並且它似乎*可以正常工作。 – Joe 2009-06-24 16:52:16

+0

謝謝@Joe - 編輯我的答案 – d4nt 2009-06-29 09:05:39

4

我這個頁面知道同樣的事情上結束。下面是我在做什麼(我不喜歡,但似乎只是正常工作):

HttpContext context = HttpContext.Current; 
if (context == null) 
{ 
    HttpRequest request = new HttpRequest(string.Empty, "http://tempuri.org", string.Empty); 
    HttpResponse response = new HttpResponse(new StreamWriter(new MemoryStream())); 
    context = new HttpContext(request, response); 
    HttpContext.Current = context; 
} 
this.cache = context.Cache; 
28

雖然OP指定的v3.5版本,有人問發佈V4之前。爲了幫助任何人發現這個問題可以生活在v4依賴項中,框架團隊爲這種類型的場景創建了一個新的通用緩存。它在System.Runtime.Caching命名空間: http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

靜態參考默認緩存實例是:MemoryCache.Default

相關問題