ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

How to use In Memory Cache in ASP.NET Core?

.Net .Net Core about 7 years ago || 8/29/2018 || 5.0 K View

  • Hide

Today I got one question regarding caching in .NET Core, so I thought why not to provide a small detail about how to use In Memory Cache in ASP.NET Core 2.x. In .NET Core, it's easy to use caching with the help of Middleware. If you want to know more about Middleware then visit https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

 

So how to use In Memory Cache in ASP.NET Core? In order to use In Memory Cache in ASP.NET Core, first, we need to have a NuGet Package i.e. Microsoft.Extensions.Caching.Memory we can install it directly with NuGet Package Manager in Visual Studio or with NPM Console or Directly add/edit in Project.csproj file in like.

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.1.2" />
</ItemGroup>

An Image with NuGet Package Manager is shown below,

So once you got NuGet Package now next step is to add a Middleware from startup.cs in ConfigureServices section, just after services.AddMvc() line like

services.AddMemoryCache();

Now setup part is done now where we want to do In Memory Cache we just have to initialize it and set the value in In Memory Cache and we can get it where we need it.

An Example of Initialization in Home Controller is given below,

//A Deceleration
IMemoryCache _memoryCache;
//Initialization in a constructor of Home Controller
public HomeController(IMemoryCache memoryCache)
{
    _memoryCache = memoryCache;
}

Now to set and get value from In Memory Cache I just created a dummy method for getting a list of projects. So a method will return list of the project from In Memory Cache if it is not null else it will get data from the database and set it in In Memory Cache and return a project list.This method has async signature as .NET Core supports well async, but it is not necessary to use async in In Memory Cache it's up to your need. In the above method, I retrieved data from the database with async method so I just added it async.

private async Task<List<ProjectInfo>> GetProjectList()
{
    MemoryCacheEntryOptions cacheOption = new MemoryCacheEntryOptions()
    {
        //As per your application logic you set a time for Caching
        //For this example I had created Cache duration of 30 minutes
        AbsoluteExpirationRelativeToNow = (DateTime.Now.AddMinutes(30) - DateTime.Now)
    };

    List<ProjectInfo> objProjectList;
    //if Cache key is not null then get data from cache else load data from database and set into cache so that it is usable for next time
    if (_memoryCache.Get("ProjectList") != null)
    {
        objProjectList = (List<ProjectInfo>)_memoryCache.Get("ProjectList");
    }
    else
    {
        GenralCRUD objCRUID = new GenralCRUD();
        //Get List of Projects from Database, as we all know how to get data fraom database that section is excluded from this article scope.
        objProjectList = await objCRUID.GetProjectList();
        _memoryCache.Set("ProjectList", objProjectList, cacheOption);
    }
    return objProjectList;
}

Note:- Be sure that a data that you want to store in a cache can be stored in Server memory, if you do not have enough memory then it can result in a bad performance for your application as this caching data is stored in server memory and it's always finite in nature.

So it's a very cool feature of .NET Core to use In Memory Cache with just a few small setups and you have done it. Hope you like.

  • 3
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Alok Pandey

Alok Pandey

Love to share what I know.

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey