2011-09-07 63 views
1

其實我爲我的網頁配置使用xml文件,xml文件包含所有內容,所有的控件/內容都通過這些XML文件加載並且工作,這些配置文件可以動態變化,網頁只是改變他們的佈局/內容,不需要重新編譯/重新部署,我必須保持這種做事方式。一種加載XML文件一次的方法.net c#

問題是,我加載這些文件,如每頁20次,當我想從我的類/ ashx文件訪問它們,我只是不斷打開它們。有沒有辦法加載xml文件,因爲它們是全局資源,並從我的classes/cs/ashx文件訪問內容?

問題與全球資源的是,如果將其添加爲emmbded 資源,我不能沒有recompling他們指的 this post改變它們。如我錯了請糾正我。

謝謝。

+0

您是否需要在運行時更改這些文件或者只是讀取它們? –

回答

3

您可以將文件存儲在CacheSessionApplicationViewState對象中。

我覺得最好的是Cache對象,因爲你可以添加一些dependencies based on files,和你的對象會自動更新:

Cache.Insert("CacheItem4", "Cached Item 4", new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"))); 
+0

謝謝,我從來沒有想過這樣。 – Flob

0

您需要訪問您的文件,這將有類似的屬性創建包裝:

public class MyMarkupProvider 
{ 
    public XDocument HomePageLayout {get;set;} 
} 

此外,它會創建緩存這些文件。以使用高速緩存和文件的CacheDependency一看:Cache files using ASP.NET Cache Dependency

2

在這樣的情況下,我使用了一個幫手:

public class CacheUtil 
{ 
    private static readonly object locker=new object(); 
    public static T GetCachedItem<T>(string cacheKey, 
            Func<T> valueCreateFunc, 
            TimeSpan duration) 
    { 
     var expirationTime = DateTime.UtcNow + duration; 
     var cachedItem = HttpRuntime.Cache[cacheKey]; 
     if (cachedItem == null) 
     { 
      lock(locker) 
      { 
       cachedItem = HttpRuntime.Cache[cacheKey]; 
       if (cachedItem == null) 
       { 
        cachedItem = valueCreateFunc(); 
        HttpRuntime.Cache.Add(cacheKey, 
              cachedItem, 
              null, 
              expirationTime, 
              Cache.NoSlidingExpiration, 
              CacheItemPriority.High, 
              null); 
       } 
      } 

     } 
     return (T) cachedItem; 
    } 
} 

,我會使用這樣的:

CacheUtil.GetCachedItem(
    "someUniqueKey", 
    ()=>{ //fetch resource from disk 
      return value;}, 
    TimeSpan.FromDays(1) 
) 

提供的委託只會每天調用一次。如果該項目已在緩存中,則不會再次調用該委託。

+2

使用CacheDependency過期而不是持續時間會更好。這樣一旦文件發生變化,緩存就會被更新,否則就不會(除了當asp.net因爲自己的原因決定將緩存過期時)。 –

+0

是的。 CacheDependency對我來說是新的,我一直在閱讀文檔,因爲閱讀了其他一些答案,並認爲它可能在這種情況下更有用。 – spender

相關問題