Where to store AppFabric DataCacheFactory in Asp.n

2019-04-02 02:13发布

问题:

AppFabric's DataCacheFactory takes long time to initialize so I am trying to create it once and re-use it in next requests.

Currently, the best idea I have is to store it in HttpContext but I also have some WCF services (which don't have HttpContext set). Any other ideas where and how I should handle this?

Thanks!

回答1:

This is a problem I've been giving some thought to over the last couple of months, but I haven't come up with a definitive answer...

I'm not sure HttpContext is the right place to keep it - according to this page "A new HttpContext object will be created at the beginning of a request and destroyed when the request is completed", so I'd be concerned that if you put DataCacheFactory into HttpContext you're going to lose it when the request pipeline completes. (HttpContext isn't an object I've particularly needed to use so I could have this completely wrong!)

However, I think there are a number of options:

  • If you use the Singleton pattern for creating a DataCacheFactory (Jon Skeet has an excellent piece on doing Singletons in C# with thread-safety here), the Singleton will essentially take care of storing the DataCacheFactory for you in the instance field.

  • This option feels slightly perverse but you could keep your DataCacheFactory in the ASP.NET Cache. Not being a WCF developer I don't know what you've got access to but if you can get to the HttpRuntime object the cache is accessible from there.

  • Another option you might want to consider is storing DataCacheFactory in Application state, although I think this might also be difficult to access from your WCF services as it's typically accessed through HttpContext.



回答2:

I have a solution for this problem in WCF using MemoryCache. Store the AppFabric cache object in memory so you don't have to call the expensive initialization of the DataCacheFactory.

Private Shared _memCache As MemoryCache

Public Shared ReadOnly Property Cache As DataCache
    Get
        If _memCache Is Nothing Then
            _memCache = MemoryCache.Default
            Dim factory As New DataCacheFactory
            _memCache("memCache") = factory.GetCache("appFabricCache")
        End If
        Return CType(_memCache("memCache"), DataCache)
    End Get
End Property

Trying to use HttpContext is not the way to go in WCF.

Libraries you'll need to include for this:

Imports System.Runtime.Caching
Imports Microsoft.ApplicationServer.Caching