Why use System.Runtime.Caching or System.Web.Caching Vs static variables?

后端 未结 3 1724
轻奢々
轻奢々 2020-12-25 11:56

Long time listener - first time caller. I am hoping to get some advice. I have been reading about caching in .net - both with System.Web.Caching and System.Runtime.Caching

相关标签:
3条回答
  • 2020-12-25 12:25

    First of all, Xaqron makes a good point that what you're talking about probably doesn't qualify as caching. It's really just a lazily-loaded globally-accessible variable. That's fine: as a practical programmer, there's no point bending over backward to implement full-on caching where it's not really beneficial. If you're going to use this approach, though, you might as well be Lazy and let .NET 4 do the heavy lifting:

    private static Lazy<IEnumerable<Category>> _allCategories
        = new Lazy<IEnumerable<Category>>(() => /* Db call to populate */);
    
    public static IEnumerable<Category> AllCategories 
    { 
        get { return _allCategories.Value; } 
    }
    

    I took the liberty of changing the type to IEnumerable<Category> to prevent callers from thinking they can add to this list.

    That said, any time you're accessing a public static member, you're missing out on a lot of flexibility that Object-Oriented Programming has to offer. I'd personally recommend that you:

    1. Rename the class to CategoryRepository (or something like that),
    2. Make this class implement an ICategoryRepository interface, with a GetAllCategories() method on the interface, and
    3. Have this interface be constructor-injected into any classes that need it.

    This approach will make it possible for you to unit test classes that are supposed to do things with all the categories, with full control over which "categories" are tested, and without the need for a database call.

    0 讨论(0)
  • 2020-12-25 12:32

    Other than expiration (and I wouldn't want this to expire) ...

    If you don't care about the life-time the name is not caching anymore.

    Still using Application (your case) and Session object are best practices for storing application level and session level data.

    0 讨论(0)
  • 2020-12-25 12:34

    System.Runtime.Caching and System.Web.Caching have automatic expiration control, that can be based on file-changes, SQL Server DB changes, and you can implement your own "changes provider". You can even create dependecies between cache entries.

    See this link to know more about the System.Caching namespace:

    http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx

    All of the features I have mentioned are documented in the link.

    Using static variables, would require manual control of expiration, and you would have to use file system watchers and others that are provided in the caching namespace.

    0 讨论(0)
提交回复
热议问题