Simple Memory Cache in ASP.NET Core
In this blog post, we'll explore how to use in-memory caching in ASP.NET Core. Caching can highly enhance the performance of your web application by reducing the number of times data needs to be retrieved or computed. We'll use a simple example to illustrate how you can implement in-memory caching in your ASP.NET Core application.
Setting Up the Project
First, let's set up our ASP.NET Core project. We'll start with the HomeController class, which will handle our web requests.
Here's the code for our HomeController:
How It Works
1. Dependency Injection:
- The HomeController constructor takes two parameters: ILogger<HomeController> and IMemoryCache.
- ASP.NET Core's dependency injection (DI) system provides these services automatically.
2. Caching Logic:
- Inside the Index action, we define a cache key, CachedDateTime.
- We use _memoryCache.TryGetValue to check if the value associated with this key is already in the cache.
- If the value is not in the cache, we set it to the current date and time (DateTime.Now.ToString("F")).
- We define cache options using MemoryCacheEntryOptions to set an absolute expiration time of 10 seconds.
- We store the value in the cache with _memoryCache.Set.
3. Passing Data to the View:
- The cached value (current date and time) is passed to the view using ViewData.
Configuring Memory Cache
To enable memory caching, we need to add the memory cache service in the program.cs file:
This line registers the memory cache service with the ASP.NET Core dependency injection container.
Creating the View
Finally, let's create a simple view to display the cached date and time. Open the Index.cshtml file in the Views/Home directory and add the following code:Running the Application
Run your application and navigate to the home page. You should see the current date and time displayed. Refresh the page within 10 seconds, and you'll see the same date and time due to the caching. After 10 seconds, the cached value expires, and you'll see the updated date and time on the next refresh.
Conclusion
In this blog post, we've seen how to implement in-memory caching in an ASP.NET Core application. This simple example demonstrates the power of caching to improve performance by reducing redundant data fetching or computation. With just a few lines of code, you can easily integrate caching into your applications and provide a better experience for your users.
Comments
Post a Comment