MemoryCache problem fixes for. NET Core 2.0 Migration Tips

Source: Internet
Author: User

For traditional. NET framework projects, the System.Runtime.Caching namespace is a common tool, where the MemoryCache class is often used to implement memory caching.

. NET Core 2.0 temporarily does not support System.Runtime.Caching DLLs, which means that memorycache related code no longer works.

But the good news is that we can use the new API for. NET Core 2.0 to implement the memory caching feature, simply modify the code to address incompatibility issues.

Solution Solutions

1. Import the old code into the project as follows:

usingSystem;usingSystem.Runtime.Caching;namespacetestwebapp.service{ Public classMemorycacheservice {StaticObjectCache cache =Memorycache.default; /// <summary>        ///Get Cache value/// </summary>        /// <param name= "key" ></param>        /// <returns></returns>        Private ObjectGetcachevalue (stringkey) {            if(Key! =NULL&&Cache. Contains (key)) {returnCache[key]; }            return default(Object); }        /// <summary>        ///Add cached Content/// </summary>        /// <param name= "key" ></param>        /// <param name= "value" ></param>         Public Static voidSetchachevalue (stringKeyObjectvalue) {            if(Key! =NULL) {cacheitempolicy policy=NewCacheItemPolicy {slidingexpiration= Timespan.fromhours (1)                                    }; Cache.            Set (key, value, policy); }        }    }}

After importing you will find that vs will not be able to find the System.Runtime.Caching namespace, and the original code cannot be compiled directly.

2. Add the Microsoft.Extensions.Caching.Memorynamespace, which provides the default implementation of the. NET Core MemoryCacheClass, and a new memory cache API

  

using Microsoft.Extensions.Caching.Memory;

3. Rewrite the code and implement the memory caching function with the new API

Initialize cache object mode before overwriting:

Static ObjectCache cache = Memorycache.default;

After the Initialize cache object mode is overwritten:

Static New MemoryCache (new memorycacheoptions ());

Read memory Cache value change mode:

Private Object Getcachevalue (string  key) {    ifnull && cache. Contains (key))    {        return  Cache[key];    }     return default (object);}

After rewriting:

Private Object Getcachevalue (string  key) {    objectnull;     if NULL  out val))    {        return  val;    }     Else     {        returndefault(object);}    }

To set the memory cache content mode change:

 Public Static void Setchachevalue (stringobject  value) {    ifnull)    {         New  cacheitempolicy        {            = timespan.fromhours (1)        };        Cache. Set (key, value, policy);}    }

After modification:

 Public Static void Setchachevalue (stringobject  value) {    ifnull)    {         New  memorycacheentryoptions        {            = timespan.fromhours (1)        });    }}

Conclusion

After rewriting the old code with the new API under Microsoft.Extensions.Caching.Memory, you will find that the original memory cache timeout policies all have corresponding new APIs, including Absoluteexpiration, SlidingExpiration and so on.

So we can still easily use. NET Core new API simple changes under the can reuse most of the existing old code, migrate it to continue to work.

The complete code after the migration is as follows:

usingMicrosoft.Extensions.Caching.Memory;usingSystem;namespacetestmemorycachewebapp.services{ Public classMemorycacheservice {StaticMemoryCache cache =NewMemoryCache (Newmemorycacheoptions ()); /// <summary>        ///Get Cache value/// </summary>        /// <param name= "key" ></param>        /// <returns></returns>        Private ObjectGetcachevalue (stringkey) {            Objectval =NULL; if(Key! =NULL&& Cache. TryGetValue (Key, outval)) {                returnVal; }            Else            {                return default(Object); }        }        /// <summary>        ///Add cached Content/// </summary>        /// <param name= "key" ></param>        /// <param name= "value" ></param>         Public Static voidSetchachevalue (stringKeyObjectvalue) {            if(Key! =NULL) {cache. Set (key, value,Newmemorycacheentryoptions {slidingexpiration= Timespan.fromhours (1)                }); }        }    }}

MemoryCache problem fixes for. NET Core 2.0 Migration Tips

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.