Using MemoryCache in ASP. NET Core 2.0

Source: Internet
Author: User

When it comes to memory caching, you might immediately think of Httpruntime.cache, which is located under the System.Web namespace, but system.web no longer exists in ASP. Just talk about it today. How to use memory caching in ASP. We generally have access to the cache of data that is often accessed but not often changed, which can significantly improve the performance of your application. About MemoryCache on GitHub address: https://github.com/aspnet/Caching Total 4 items

The first item is the cache abstraction, the other three are different types Memory,redis,sqserver

First, you need to register the cache service in Configureservices

public void Configureservices (iservicecollection services) {    services. Addmemorycache ();    Services. Addmvc ();}

Get the IMemoryCache instance from the home Controller's constructor in the following code

public class homecontroller:controller{    private IMemoryCache _cache;    Public HomeController (IMemoryCache memorycache)    {        _cache = MemoryCache;    }}

About the use of the cache is commonly used is set Get Remove, some people like to encapsulate the code in a separate class library, I think it is not necessary, it can be directly used in our web project directly, and the Imemory provides the extension method is the best package

Set the cache set

_cache. Set ("Key", "value");

Get Cache get

var result = _cache. Getorcreate ("MyKey", (entry) =>{    entry. Absoluteexpirationrelativetonow = Timespan.fromseconds (+);    return DateTime.Now.ToString ();});

Remove Cache Remove

_cache. Remove ("key");

Using MemoryCache in ASP. NET Core 2.0

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.