<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net core cache &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-cache/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>Help you to find best ASP.NET Core Hosting</description>
	<lastBuildDate>Tue, 17 Jan 2023 04:28:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net core cache &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Implement Distributed Cache in ASP.NET Core</title>
		<link>https://topreviewhostingasp.net/how-to-implement-distributed-cache-in-asp-net-core/</link>
					<comments>https://topreviewhostingasp.net/how-to-implement-distributed-cache-in-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Tue, 17 Jan 2023 04:28:41 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core cache]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[asp net tips]]></category>
		<category><![CDATA[distributed cache asp net]]></category>
		<category><![CDATA[implement distributed cache]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3348</guid>

					<description><![CDATA[A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm. This article will [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm.</p>



<p>This article will take you though some of the basic concepts of c# like Generic and asp.net core <strong>Dependency Injection</strong> and most importantly <strong>Distributed Caching</strong>, a reusable component. Caching is a very useful part of large applications, it minimizes the cost of making DB calls in API request. Here we will be implementing Distributed Caching. Let’s go ahead and get started.</p>



<h2 class="wp-block-heading">Steps by Steps to Implement Distributed Caching</h2>



<p><strong>1. Create new project</strong></p>



<p>Search for ASP.NET core web application and select it. Then click on Next</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="549" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1-1024x549.webp" alt="" class="wp-image-3349" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1-1024x549.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1-300x161.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1-768x412.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1-50x27.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_1.webp 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Name the Project <strong>DistributedCaching</strong> and select all dropdown according to above selection. Then click on Create</figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="551" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2-1024x551.webp" alt="" class="wp-image-3350" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2-1024x551.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2-300x162.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2-768x414.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2-50x27.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_2.webp 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Choose API on next screen</figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="549" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3-1024x549.webp" alt="" class="wp-image-3351" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3-1024x549.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3-300x161.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3-768x412.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3-50x27.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/VS_3.webp 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure></div>


<p><strong>2. Package Installation</strong></p>



<p id="e6aa">Right-click on Project Solution select Manage Nuget Package and Install the following packages</p>



<p id="b1f7">· System.Data.SqlClient</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="93" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql.webp" alt="" class="wp-image-3352" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql.webp 720w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-300x39.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-50x6.webp 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure></div>


<p><strong>3. Configuration</strong></p>



<p id="b321">After the project creation, go to <strong>Startup.cs. </strong>In the ConfigureServices method, we need to add Distributed Memory Cache service.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="144" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/configuration.webp" alt="" class="wp-image-3353" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/configuration.webp 720w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/configuration-300x60.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/configuration-50x10.webp 50w" sizes="(max-width: 720px) 100vw, 720px" /><figcaption>In appsettings.json, we need to write our SQL server data source, user, password, and database that will be used by our project.</figcaption></figure></div>


<pre class="wp-block-preformatted">"ConnectionStrings": {"SqlServerCString": "Data Source=localhost;Initial Catalog=caching;Persist Security Info=True;User ID=sa;Password=1234;"}</pre>



<p id="8a90">A complete view of appsettings.json</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="244" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring-1024x244.webp" alt="" class="wp-image-3354" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring-1024x244.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring-300x71.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring-768x183.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring-50x12.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/connectionstring.webp 1108w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure></div>


<p><strong>4. Create Database</strong></p>



<ul><li>Open your SQL Server Management Studio and create a database named <strong>caching.</strong></li><li>Then open your query window and create a table named <strong>Student</strong> with the following query and insert some data using the following query</li></ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="661" height="192" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-query.webp" alt="" class="wp-image-3355" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-query.webp 661w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-query-300x87.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/sql-query-50x15.webp 50w" sizes="(max-width: 661px) 100vw, 661px" /></figure></div>


<p><strong>5. Create Controller</strong></p>



<p id="dbdf">Click on the Controllers folder and add a new Controller. On the next screen select <strong>API Controller Empty </strong>and Click on <strong>Add</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="707" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller-1024x707.webp" alt="" class="wp-image-3356" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller-1024x707.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller-300x207.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller-768x531.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller-50x35.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/controller.webp 1174w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>On the next screen name the controller <strong>CachingController </strong>and click on Add</figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="709" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller-1024x709.webp" alt="" class="wp-image-3357" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller-1024x709.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller-300x208.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller-768x532.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller-50x35.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/cachingcontroller.webp 1175w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Then open CachingController and do the following</figcaption></figure></div>


<pre class="wp-block-preformatted">[Route("api/[controller]")]</pre>



<p>to</p>



<pre class="wp-block-preformatted">[Route("api/caching")]</pre>



<p><strong>6. Create Database Model</strong></p>



<p id="dc87">Create a folder and name it Model, add Student.cs with the following code. Make Model serializable for further serializing in setting cache</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="206" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-1024x206.webp" alt="" class="wp-image-3358" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-1024x206.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-300x60.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-768x154.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-50x10.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model.webp 1400w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure></div>


<p id="ad3f">Place the below code inside CachingController</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="865" height="795" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-2.webp" alt="" class="wp-image-3359" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-2.webp 865w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-2-300x276.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-2-768x706.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/database-model-2-50x46.webp 50w" sizes="(max-width: 865px) 100vw, 865px" /><figcaption>After placing code, make a request from <strong>POSTMAN </strong>to <a href="https://localhost:%3cPORT%3e/api/caching" target="_blank" rel="noreferrer noopener">https://localhost:&lt;PORT>/api/caching</a> and you will get back the following response. You can notice response time <strong>1348 MS</strong></figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="443" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/code-1024x443.webp" alt="" class="wp-image-3360" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/code-1024x443.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/code-300x130.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/code-768x332.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/code-50x22.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/code.webp 1265w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Create a folder Service and add MemoryCache.cs class and IMemoryCache.cs with the following code.</figcaption></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="287" height="288" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache.webp" alt="" class="wp-image-3361" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache.webp 287w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache-150x150.webp 150w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache-50x50.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache-70x70.webp 70w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache-127x127.webp 127w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/distributecache-125x125.webp 125w" sizes="(max-width: 287px) 100vw, 287px" /></figure></div>


<p id="88ae">IMemoryCache.cs</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="513" height="171" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/imemorycache.webp" alt="" class="wp-image-3362" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/imemorycache.webp 513w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/imemorycache-300x100.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/imemorycache-50x17.webp 50w" sizes="(max-width: 513px) 100vw, 513px" /></figure></div>


<p id="539e">MemoryCache.cs</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="735" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache.webp" alt="" class="wp-image-3363" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache.webp 720w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache-294x300.webp 294w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache-50x50.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache-70x70.webp 70w" sizes="(max-width: 720px) 100vw, 720px" /></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="648" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_2.webp" alt="" class="wp-image-3364" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_2.webp 720w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_2-300x270.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_2-50x45.webp 50w" sizes="(max-width: 720px) 100vw, 720px" /></figure></div>


<p id="773b">After placing all code accordingly, we will do <strong>Dependency Injection</strong> MemoryCache in <strong>Startup.cs</strong>. Add the following code inside the <strong>ConfigureServices</strong> method</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="513" height="171" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_3.webp" alt="" class="wp-image-3365" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_3.webp 513w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_3-300x100.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_3-50x17.webp 50w" sizes="(max-width: 513px) 100vw, 513px" /></figure></div>


<p id="f4ea">Now&nbsp;<strong>MemoryCache&nbsp;</strong>implementation available throughout Application Lifetime and an instance will be created every time there will be a request to the server.</p>



<p id="d1a3">Now let’s go for caching the result after fetching data from Student Table</p>



<ul><li>First, let’s receive MemoryCache through Constructor Injection in CachingController.cs with the following code.</li></ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="702" height="169" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_4.webp" alt="" class="wp-image-3366" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_4.webp 702w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_4-300x72.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_4-50x12.webp 50w" sizes="(max-width: 702px) 100vw, 702px" /></figure></div>


<ul><li>Let’s cache student list after fetching data from Student Table, update the GetResult method in CachingController with the following code</li></ul>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="662" height="656" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5.webp" alt="" class="wp-image-3367" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5.webp 662w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-300x297.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-150x150.webp 150w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-50x50.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-70x70.webp 70w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-127x127.webp 127w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_5-125x125.webp 125w" sizes="(max-width: 662px) 100vw, 662px" /></figure></div>


<p>So now fetched data from DB is now stored in a cache, now we have to check if student data available in the cache then fetch data from the cache otherwise make DB call and store it in the cache using the same method. Update the GetResult method with the following code.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="720" height="805" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_6.webp" alt="" class="wp-image-3368" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_6.webp 720w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_6-268x300.webp 268w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/memorycache_6-45x50.webp 45w" sizes="(max-width: 720px) 100vw, 720px" /></figure></div>


<p>So now make a request from POSTMAN to <a href="https://localhost:%3cPORT%3e/api/caching" target="_blank" rel="noreferrer noopener">https://localhost:&lt;PORT>/api/caching</a> and see the difference in response time</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="448" src="https://topreviewhostingasp.net/wp-content/uploads/2023/01/1-1024x448.webp" alt="" class="wp-image-3369" srcset="https://topreviewhostingasp.net/wp-content/uploads/2023/01/1-1024x448.webp 1024w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/1-300x131.webp 300w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/1-768x336.webp 768w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/1-50x22.webp 50w, https://topreviewhostingasp.net/wp-content/uploads/2023/01/1.webp 1267w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure></div>


<p id="f4fc">You can see time&nbsp;<strong>7 MS</strong>, this makes a huge difference in server efficiency using the caching method.</p>



<p id="3402">Now, we have created a service that will be injected in Startup.cs file, a component that can be used in any project for caching. One more point if you want to remove a particular cache from memory then in the same way call <strong>removeCache</strong> and pass the <strong>CacheKeys</strong> inside the function. It will remove cache from memory.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-implement-distributed-cache-in-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>10 Things You Need to Know About ASP.NET Core Memory Caching</title>
		<link>https://topreviewhostingasp.net/10-things-you-need-to-know-about-asp-net-core-memory-caching/</link>
					<comments>https://topreviewhostingasp.net/10-things-you-need-to-know-about-asp-net-core-memory-caching/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 16 Jul 2021 07:08:12 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core cache]]></category>
		<category><![CDATA[asp net core memory caching]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2977</guid>

					<description><![CDATA[The primary purpose of any caching mechanism is to improve performance of an application. As an ASP.NET developer you are probably aware that ASP.NET web forms as well as ASP.NET MVC could used Cache object to cache application data. This was often called server side data caching and was available as an inbuilt feature of [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>The primary purpose of any caching mechanism is to improve performance of an application. As an ASP.NET developer you are probably aware that ASP.NET web forms as well as ASP.NET MVC could used Cache object to cache application data. This was often called server side data caching and was available as an inbuilt feature of the framework. Although ASP.NET Core doesn&#8217;t have Cache object as such, you can implement in-memory caching quite easily. This article shows you how.</p>



<p>Before you read any further create a new ASP.NET Core application based on Web Application project template.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="592" height="385" class="wp-image-2978 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_1.png 592w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_1-300x195.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_1-50x33.png 50w" sizes="(max-width: 592px) 100vw, 592px" /></figure>
</div>



<p>Then follow the steps mentioned below one-by-one to build and test various features offered by in-memory caching.</p>



<h2 class="wp-block-heading">1. In-memory caching needs to enabled in the Startup class</h2>



<p>Unlike ASP.NET web forms and ASP.NET MVC, ASP.NET Core doesn&#8217;t have the built-in Cache object that you can directly used inside controllers. Here, in-memory caching works through dependency injection and hence the first step is to register the in-memory caching service in the Startup class. So, open the Startup class and locate the ConfigureServices() method. Modify the ConfigureServices() method to look like this:</p>



<pre class="wp-block-preformatted">public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
<strong>    services.AddMemoryCache();
</strong>}</pre>



<p>To add in-memory caching capabilities to your application you need to call AddMemoryCache() method on the services collection. This way the default implementation of an in-memory cache &#8211; an IMemoryCache object &#8211; can be injected to the controllers. </p>



<h2 class="wp-block-heading">2. In-memory caching uses dependency injection to inject the cache object</h2>



<p>Then open the HomeController and modify it as shown below:</p>



<pre class="wp-block-preformatted">public class HomeController : Controller
{
<strong>    private IMemoryCache cache;
</strong>
    public HomeController(<strong>IMemoryCache cache</strong>)
    {
        this.cache = cache;
    }
    ....
}</pre>



<p>As you can see, the above code declares a private variable of ImemoryCache. This variable gets assigned in the constructor. The constructor receives the cache parameter through DI and then this cache object is stored in the local variable for later use. </p>



<h2 class="wp-block-heading">3. You can use Set() method to store an item in the cache</h2>



<p>Once you have IMemoryCache object, you can read and write items or entries to it. Adding an entry into the cache is quite straightforward.</p>



<pre class="wp-block-preformatted">public IActionResult Index()
{
<strong>  cache.Set&lt;string&gt;("timestamp", DateTime.Now.ToString());
</strong>  return View();
}</pre>



<p>The above code sets a cache entry in the Index() action. This is done using Set&lt;T&gt;() method of IMemoryCache. The first parameter to Set() method is a key name by which the entry will be identified. The second parameter is the value of the key. In this example we store a string key and string value but you can store other types (primitive types and custom types) also. </p>



<h2 class="wp-block-heading">4. You can use Get() method to retrieve an item from the cache</h2>



<p>Once you add an item into the cache, you would like to retrieve it elsewhere in the application. You can do so using the Get() method. The following code shows how.</p>



<pre class="wp-block-preformatted">public IActionResult Show()
{
<strong>  string timestamp = cache.Get&lt;string&gt;("timestamp");
</strong>  return View("Show",timestamp);
}</pre>



<p>The above code retrieves a cached item from another action (Show) of the HomeController. The Get() method specifies the type of the item and its key. The item, if present, will be returned and assigned to timestamp string variable. This timestamp value is then passed to Show view.</p>



<p>The Show view simply outputs the timestamp value as shown below:</p>



<pre class="wp-block-preformatted">&lt;h1&gt;TimeStamp : @Model&lt;/h1&gt;

&lt;h2&gt;@Html.ActionLink("Go back", "Index", "Home")&lt;/h2&gt;</pre>



<p>To test what you wrote so far, run the application. Navigate to /Home/Index first so that timestamp key is assigned. Then navigate to /Home/Show and see whether timestamp value gets outputted. The following image shows a sample run of the Show() action.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="599" height="271" class="wp-image-2979 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_2.png 599w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_2-300x136.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_2-50x23.png 50w" sizes="(max-width: 599px) 100vw, 599px" /></figure>
</div>



<h2 class="wp-block-heading">5. You can use TryGet() to check whether a key is present in the cache</h2>



<p>If you observe the previous example, you will find that every time you navigate to the /Home/Index, a new timestamp is assigned to the cached item. This is because we didn&#8217;t put any check to assign the value only if the item doesn&#8217;t exists. Many a times you would like to do just that. There are two ways to perform that check inside Index() action. Both are shown below:</p>



<pre class="wp-block-preformatted">//first way
if (<strong>string.IsNullOrEmpty
(cache.Get&lt;string&gt;("timestamp"))</strong>)
{
  cache.Set&lt;string&gt;("timestamp", DateTime.Now.ToString());
}

//second way
if (!<strong>cache.TryGetValue&lt;string&gt;
("timestamp", out string timestamp)</strong>)
{
    cache.Set&lt;string&gt;("timestamp", DateTime.Now.ToString());
}</pre>



<p>The first way uses the same Get() method you used earlier. However, this time it is used along with an if block. If the Get() can&#8217;t find the specified item in the cache, IsNullOrEmpty() will return true. And only then Set() gets called to add that item.</p>



<p>The second way is more elegant. It uses TryGet() method to retrieve an item. The TryGet() method returns a boolean value indicating whether the item was found or not. The actual item can be pulled out using an output parameter. If TryGet() returns false, Set() is used to add that entry. </p>



<h2 class="wp-block-heading">6. You can use GetOrCreate() to add an item if doesn&#8217;t exist</h2>



<p>Sometimes you need to retrieve an existing item from the cache. And if that item doesn&#8217;t exist you want it to be added. These two tasks &#8211; get if it exist OR create it if it doesn&#8217;t &#8211; can be accomplished using GetOrCreate() method. The modified Show() method shows how this can be done.</p>



<pre class="wp-block-preformatted">public IActionResult Show()
{
<strong>  string timestamp = cache.GetOrCreate&lt;string&gt;
  ("timestamp", entry =&gt; { 
return DateTime.Now.ToString(); });
</strong>  return View("Show",timestamp);
}</pre>



<p>The Show() action now uses GetOrCreate() method. The GetOrCreate() method checks whether timestamp key is present or not. If yes the existing value will be assigned to the local variable. Otherwise a new entry is created and added to the cache based on the logic specified in the second parameter.</p>



<p>To test this code run /Home/Show directly without navigating to /Home/Index. You will still see a timestamp value outputted because GetOrCreate() now adds it if it isn&#8217;t already present.</p>



<h2 class="wp-block-heading">7. You can set absolute and sliding expiration on a cached item</h2>



<p>In the preceding examples, a cache item once added remains in the cache unless it is explicitly removed using the Remove() method. You can also set absolute expiration and sliding expiration on a cached item. An absolute expiration means a cached item will be removed an an explicit date and time. Sliding expiration means a cached item will be removed it is remains idle (not accessed) for a certain amount of time.</p>



<p>To set either of these expiration policies on a cached item you use MemoryCacheEntryOptions object. The following code shows how MemoryCacheEntryOptions can be used.</p>



<pre class="wp-block-preformatted">MemoryCacheEntryOptions options = 
new MemoryCacheEntryOptions();
<strong>options.AbsoluteExpiration = 
DateTime.Now.AddMinutes(1);
</strong><strong>options.SlidingExpiration = 
TimeSpan.FromMinutes(1);
</strong>cache.Set&lt;string&gt;("timestamp", 
DateTime.Now.ToString(), options);</pre>



<p>The above code from the modified Index() action creates an object of MemoryCacheEntryOptions. It then sets AbsoluteExpiration property to a DateTime value one minute from now. It also sets the SlidingExpiration property to one minute. These values indicate that the item will be removed from the cache after one minute irrespective of whether it is accessed or not. Moreover, if that item remains idle for one minute it will be removed from the cache.</p>



<p>Once the AbsoluteExpiration and SlidingExpiration values are set, the Set() method is used to add an item to the cache. This time the MemoryCacheEntryOptions object is passed as the third parameter of the Set() method.</p>



<h2 class="wp-block-heading">8. You can wire a callback when an item is removed from the cache</h2>



<p>At times you may want to be notified whenever a cached item is removed from the cache. There could be several reasons why an item gets removed from cache. For example, an item might get removed due to explicit call to Remove() method, it might get removed because its AbsoluteExpiration or SlidingExpiration values were reached and so on.</p>



<p>To know when an item is removed from the cache you need to wire a callback function. The following code shows how that is done.</p>



<pre class="wp-block-preformatted">MemoryCacheEntryOptions options = 
new MemoryCacheEntryOptions();
options.AbsoluteExpiration = 
DateTime.Now.AddMinutes(1);
options.SlidingExpiration = 
TimeSpan.FromMinutes(1);
<strong>options.RegisterPostEvictionCallback
(MyCallback, this);
</strong>cache.Set&lt;string&gt;("timestamp", 
DateTime.Now.ToString(), options);</pre>



<p>The above code is quite similar to the previous example in that it uses MemoryCacheEntryOptions to configure the AbsoluteExpiration and SlidingExpiration. More importantly it also calls the RegisterPostEvictionCallback() method to wire a callback function just discussed. In this case the callback function name is MyCallback. The second parameter is a state object that you wish to pass to the callback function. Here we pass the HomeController instance (this points to the current HomeController object) as the state.</p>



<p>The MyCallback function mentioned looks like this:</p>



<pre class="wp-block-preformatted">private static void MyCallback(object key, object value,
EvictionReason reason, object state)
{
    var message = $"Cache entry was removed : {reason}";
    ((HomeController)state).
cache.Set("callbackMessage", message);
}</pre>



<p>Observe this code carefully. The MyCallback() is a private static function inside the HomeController class. It has four parameters. The first two parameters represent the key and value of the cached item that was just removed. The third parameter indicates the reason why the item was removed. The EvictionReason is an enumeration and holds various possible reasons such as Expired, Removed and Replaced.</p>



<p>Inside the callback function we just form a string message based on the reason of removal. We want to set this message as another cache item. This needs access to the cache object of the HomeController. That&#8217;s where the state parameter can be used. Using the state object you can get hold of the HomeController&#8217;s cache object and Set() a callbackMessage cache item.</p>



<p>The callbackMessage can be accessed from the Show() action like this:</p>



<pre class="wp-block-preformatted">public IActionResult Show()
{
  string timestamp = cache.Get&lt;string&gt;("timestamp");
<strong>  ViewData["callbackMessage"] = 
    cache.Get&lt;string&gt;("callbackMessage");</strong>
  return View("Show",timestamp);
}</pre>



<p>And finally it can be displayed on the Show view:</p>



<pre class="wp-block-preformatted">&lt;h1&gt;TimeStamp : @Model&lt;/h1&gt;

<strong>&lt;h3&gt;@ViewData["callbackMessage"]&lt;/h3&gt;
</strong>
&lt;h2&gt;@Html.ActionLink("Go back", "Index", "Home")&lt;/h2&gt;</pre>



<p>To test the callback, run the application and navigate to /Home/Index. Then navigate to /Home/Show and refresh the browser from time to time. At some point the timestamp item will expire due to its AbsoluteExpiration setting. And you will see the callbackMessage like this:</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="599" height="292" class="wp-image-2980 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_3.png 599w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_3-300x146.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_3-50x24.png 50w" sizes="(max-width: 599px) 100vw, 599px" /></figure>
</div>



<h2 class="wp-block-heading">9. You can set priority for a cached item</h2>



<p>Just as you can set the expiration policies of a cached item, you can also assign a priority value to a cached item. If server experiences shortage of memory based on this priority the items will be removed to reclaim the memory. To set the priority you use MemoryCacheEntryOptions again. </p>



<pre class="wp-block-preformatted">MemoryCacheEntryOptions options = 
new MemoryCacheEntryOptions();
<strong>options.Priority = CacheItemPriority.Normal;</strong>
cache.Set&lt;string&gt;("timestamp", 
DateTime.Now.ToString(), options);</pre>



<p>The Priority property of MemoryCacheEntryOptions allows you to set a priority value for an item using CacheItemPriority enumeration. Possible values are Low, Normal, High and NeverRemove.</p>



<h2 class="wp-block-heading">10. You can set a dependency between multiple cached items</h2>



<p>You can also set a dependency between a set of cached items such than when an item is removed all the dependent items are also removed. To see how this works, modify the Index() action as shown below:</p>



<pre class="wp-block-preformatted">public IActionResult Index()
{
    var cts = new CancellationTokenSource();
    cache.Set("cts", cts);

    MemoryCacheEntryOptions options = 
new MemoryCacheEntryOptions();
    options.AddExpirationToken(
new CancellationChangeToken(cts.Token));
    options.RegisterPostEvictionCallback
(MyCallback, this);
    cache.Set&lt;string&gt;("timestamp", 
DateTime.Now.ToString(), options);

    cache.Set&lt;string&gt;("key1", "Hello World!", 
new CancellationChangeToken(cts.Token));
    cache.Set&lt;string&gt;("key2", "Hello Universe!", 
new CancellationChangeToken(cts.Token));

    return View();
}</pre>



<p>The code begins by creating a CancellationTokenSource object and the object is stored as an independent cached item cts. Then MemoryCacheEntryOptions object is created as before. This time AddExpirationToken() method of MemoryCacheEntryOptions is called to specify an expiration token. We won&#8217;t go into the details of CancellationChangeToken here. It is suffice to say that an expiration token allows you to expire an item. If the token is active the item stays in the cache but if the token is cancelled the item is removed from the cache. Once the item is removed from the cache MyCallback is called as before. Then the code creates two more items &#8211; key1 and key2. While adding these two items the third parameter of Set() passes a CancellationChangeToken based on cts object created earlier.</p>



<p>That means here we have three keys &#8211; timestamp is the primary key, key1 and key2 are dependent on timestamp. When timestamp is removed key1 and key2 should also get removed. To remove timestamp you need to cancel its token somewhere in the code. Let&#8217;s do that in a separate action &#8211; Remove().</p>



<pre class="wp-block-preformatted">public IActionResult Remove()
{
<strong>    CancellationTokenSource cts = 
</strong><strong>cache.Get&lt;CancellationTokenSource&gt;("cts");
    cts.Cancel();</strong>
    return RedirectToAction("Show");
}</pre>



<p>Here we retrieve the CancellationTokenSource object stored earlier and call its Cancel() method. Doing so will remove timestamp, key1 as well as key2. You can confirm that by retrieving all these three keys in the Show() action.</p>



<p>In order to test this example, run the application and navigate to /Home/Index. Then navigate to /Home/Show and check whether all the three key values are being shown as expected. Then navigate to /Home/Remove. You will be redirected back to /Home/Show. Since Remove() cancelled the token all the keys will be removed and now the Show view will show the reason for expiration (TokenExpired) like this:</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="599" height="292" class="wp-image-2981 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_4.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_4.png 599w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_4-300x146.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/07/image_4-50x24.png 50w" sizes="(max-width: 599px) 100vw, 599px" /></figure>
</div>



<p>Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/10-things-you-need-to-know-about-asp-net-core-memory-caching/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
