2012-11-09 25 views
0

我想能夠在應用程序的WebAPI積極RavenDB緩存,對於較大的應用程序內的操作方法。在using語句之外調用AggressivelyCacheFor(duration)有什麼影響?

爲了實現這一點,我去創建一個動作濾波器屬性,該屬性獲取IDocumentSession的路線,並在調用OnActionExecuting使積極的緩存15分鐘的方法。然後,在OnActionexecuted中,我在同一個會話中調用DisableAggressiveCaching()

總之,這導致了一些相當怪異的行爲。使用積極的緩存操作方法被調用後,後續請求其他操作方法,在反正不依賴於緩存(他們正在完全不同的要求),最終得到一個IDocumentSession其中AggressiveCacheDuration是15分鐘。發生這種情況的頻率似乎與先前調用緩存的操作方法的次數成正比。我應該補充,我正在使用StructureMap for DI,使用一個IDocumentStore單例,並注入一個HttpContextScoped IDocumentSession。我已經確認每個請求都會注入一個新的IDocumentSession,但其中一些緩存已啓用。

一些代碼,試圖進一步闡述...

的IoC - RavenRegistry

var documentStore = new DocumentStore {ConnectionStringName = "RavenDB"}; 

documentStore.Initialize(); 

For<IDocumentStore>().Singleton().Use(documentStore); 
For<IDocumentSession>().HttpContextScoped().Use(x => 
{ 
    var store = x.GetInstance<IDocumentStore>(); 
    var session = store.OpenSession(); 
    return session; 
}); 

AggressivelyCacheAttribute

public class AggressivelyCacheAttribute : ActionFilterAttribute 
{ 
    private IDocumentSession _documentSession; 

    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     base.OnActionExecuting(actionContext); 

     _documentSession = actionContext.Request.GetDependencyScope() 
      .GetService(typeof(IDocumentSession)) as IDocumentSession; 

     _documentSession.Advanced.DocumentStore 
      .AggressivelyCacheFor(TimeSpan.FromMinutes(15)); 
    } 

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 
    { 
     base.OnActionExecuted(actionExecutedContext); 
     _documentSession.Advanced.DocumentStore.DisableAggressiveCaching(); 
    } 
} 

同樣IDocumentSession然後在管道以後用來查詢數據庫,其結果被緩存。

在隨後的請求,在其中該屬性不存在的方法中,注入的IDocumentSession具有高速緩存設置爲15分鐘。這是爲什麼?

我在網上看到的唯一的例子是創建會話,其中,以高速緩存,using語句中。這是使用積極緩存的唯一「安全」方式,還是有可能做我正在嘗試的?如果是這樣,怎麼樣?

+0

我不知道這是否會工作,但你嘗試過在Application_EndRequest處置您的會話?或者只是在註冊表中禁用緩存。 – ItsJason

回答

1

基於Ayende's blogging platform code,你需要在你的過濾器類的引用:

private IDisposable _cachingHandle; 

然後當你的緩存申報,分配結果是:在

_cachingHandle = _documentSession.Advanced.DocumentStore 
    .AggressivelyCacheFor(TimeSpan.FromMinutes(15)); 

然後你執行

if(_cachingHandle != null) 
    _cachingHandle.Dispose(); 

這應該停止不必要的緩存。

+0

完成。非常感謝。 –

相關問題