开发者

A way to load XML files once .net c#

Actually i'm using xml files for my web pages configuration , xml files contain everything and all the controls/content is loadded through theese XML files and it works , theese config files can change on the fly , and web pages just change their layout/content no need to recompile/redeploy , and i must keep this way of doing things.

The problem is that i'm loading these files like 20 times per page and when i want to access them from my classes/ashx files , i just keep opening them. Is there a way to load xml Files as they were globalresources , and access content from my开发者_运维知识库 classes/cs/ashx files?

the problem with global resources is that if add them as emmbded resources , i can't change them without recompling them refering to this post . Correct me if i'm wrong.

Thanks.


You can store your files in Cache, Session, Application or ViewState objects.

I think most preferably for is Cache object, because you can add some dependencies based on files, and your objects will be automatically updated:

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


In situations like this, I use a helper:

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;
    }
}

which I would use something like this:

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

The supplied delegate will only be invoked once per day. If the item is already in cache, the delegate will not be invoked again.


You need to create wrapper for accessing your files which will have properties like:

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

Also it would be create to cache these files. Take a look on using cache and file CacheDependency: Cache files using ASP.NET Cache Dependency

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜