Search code examples
c#asp.netasp.net-mvcmemorycache

Cant get default method from MemoryCache when set as a class property


I am trying to avoid this:

 private ObjectCache cache = MemoryCache.Default

By creating a class:

public static class MemoryDefault
{
    public static MemoryCache Memory { get; set; }
}

When calling MemoryDefault.Memory.Default it does not exists, why?


Solution

  • Your property public static MemoryCache Memory { get; set; } is not initialized anywhere - so it will be always null..

    It should rather be:

    public static class MemoryDefault
    {
        static MemoryDefault()
        {
             Memory = MemoryCache.Default;
        }
    
        public static MemoryCache Memory { get; private set; }
        //private set for preventing user to change that value
    }
    

    Other approach:

    public static class MemoryDefault
    {
        public static MemoryCache Memory { get { return MemoryCache.Default; } }
    }