.NET HELP

Microsoft.Extensions.Caching.Memory Example (With PDF) in C#

Published June 6, 2024
Share:

To construct applications responsively and effectively, optimization methods are frequently needed for NET applications. Caching is a potent approach that includes temporarily storing frequently requested material in distributed cache to facilitate speedier retrieval. The reduction in processing time and server load with this strategy can lead to a significant increase in application performance. Additionally, performance counters can be implemented to monitor and enhance the caching system.

Caching is a potent optimization strategy in this context. Microsoft.Extensions.Caching.Memory provides an efficient in-memory object caching solution for .NET applications. Your PDF-centric apps will operate and respond much faster if you strategically use the MemoryCache cache along with IronPDF.

We explore how to integrate Microsoft.Extensions.Caching.Memory c# example with IronPDF efficiently. In this article, we'll discuss the advantages of caching concerning the PDF generation process, go over some useful implementation tips, and offer a detailed walkthrough for configuring caching in your IronPDF program. When all is said and done, you'll have the skills and resources necessary to develop effective and intuitive PDF applications.

Microsoft.Extensions.Caching.Memory: The Foundation of Caching in .NET

Caching is a method used in many high-performance .NET applications that stores frequently accessed data in memory for quick retrieval. Microsoft.Extensions are one of the many caching options that are accessible. Caching.Memory is a particularly strong and adaptable option. This library is a component of the larger Microsoft.Extensions.Caching namespace offers a straightforward but effective in-memory caching approach.

Key types within "Microsoft.Extensions.Caching.Memory"

IMemoryCache

  • The fundamental capability for utilizing the in-memory cache is represented by this interface. It offers ways to manage cached entries and add, retrieve, and remove them.
  • Consider it your primary point of entry for your caching processes.

MemoryCache

  • The actual implementation of IMemoryCache is in this class. It offers administration and real in-memory storage for cached items.
  • Dependency injection is usually used in ASP.NET Core applications to retrieve an instance of MemoryCache.

MemoryCacheEntryOptions

You can specify configuration settings for specific cache items with this class. These settings regulate things like:

  • Expiration: You can configure sliding expiration windows (where the entry expires if it is not accessed within a certain interval) or absolute expiration times (where the entry automatically expires).
  • Priority: When the cache fills up, this influences whether to evict items. Higher-priority entries have a lower chance of being removed.
  • Post-eviction callback: This allows you to fine-tune the logic behind handling data when it has expired. It's especially useful in scenarios where critical data needs to be refreshed, resource management, and logging.

CacheEntry

  • Within the cache, this type denotes a single entry. It offers methods and attributes to retrieve the size details, expiration settings, and cached values.
  • In essence, it contains all the information on a particular piece of data that is kept in the cache.

ICacheEntry

  • This interface outlines the basic activities that can be performed on a cache item, albeit it is not necessary for basic caching operations. It contains instructions on how to retrieve the value and expiration details. This is more prevalent in scenarios where you have the retrieve the string key.
  • This interface is implemented by the CacheEntry class, which offers a practical implementation of these features.

Install and Config Microsoft.Extensions.Caching.Memory

Microsoft.Extensions.Caching configuration. During application startup, memory is used to configure the cache service inside the ASP.NET Core application's service collection. An ASP.NET Core application that has Microsoft.Extensions.Caching.Memory configured is shown below:

Install the Required NuGet Package

First, ensure Microsoft.Extensions.Caching.Memory is installed for your project. Using the NuGet Package Manager Console, you can install it with the following command:

Install-Package Microsoft.Extensions.Caching.Memory

Or we can use NuGet Package Manager to install the package:

Microsoft.Extensions.Caching.Memory Example (With PDF) in C#: Figure 1 - Search for Microsoft.Extensions.Caching.Memory in NuGet Package Manager and install it

Configure Services in Startup.cs

Navigate to the ConfigureServices method in your ASP.NET Core app by opening the Startup.cs file. To set up the memory cache service, add the following code:

using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
    // Add memory cache service
    services.AddMemoryCache();
    // Other service configurations...
}
using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
    // Add memory cache service
    services.AddMemoryCache();
    // Other service configurations...
}
Imports Microsoft.Extensions.Caching.Memory
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Add memory cache service
	services.AddMemoryCache()
	' Other service configurations...
End Sub
VB   C#

The memory cache service object is added to the application's service collection and configured by this code. The memory cache system service is registered using its default configurations via the AddMemoryCache function.

Inject IMemoryCache

Once the cache store is set up, any class or component that needs caching can have the IMemoryCache interface injected into it. In a controller or service class, for instance:

public class MyService
{
    private readonly IMemoryCache _cache;
    public MyService(IMemoryCache cache)
    {
        _cache = cache;
    }
    // Use _cache to perform caching operations...
}
public class MyService
{
    private readonly IMemoryCache _cache;
    public MyService(IMemoryCache cache)
    {
        _cache = cache;
    }
    // Use _cache to perform caching operations...
}
Public Class MyService
	Private ReadOnly _cache As IMemoryCache
	Public Sub New(ByVal cache As IMemoryCache)
		_cache = cache
	End Sub
	' Use _cache to perform caching operations...
End Class
VB   C#

Methods for caching and retrieving data from memory are provided by the IMemoryCache interface.

Configure Cache Options

By setting cache parameters, you can alter how the memory cache behaves. This involves configuring a set method of parameters including size restrictions, cache entry eviction tactics, and cache value expiration regulations. This is an illustration of how to set cache options:

public void ConfigureServices(IServiceCollection services)
{
    // Configure cache options
    services.AddMemoryCache(options =>
    {
        options.SizeLimit = 1024; // Set the maximum size limit for the cache
        options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
        options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
    });
    // Other service configurations...
}
public void ConfigureServices(IServiceCollection services)
{
    // Configure cache options
    services.AddMemoryCache(options =>
    {
        options.SizeLimit = 1024; // Set the maximum size limit for the cache
        options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
        options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
    });
    // Other service configurations...
}
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Configure cache options
	services.AddMemoryCache(Sub(options)
		options.SizeLimit = 1024 ' Set the maximum size limit for the cache
		options.CompactionPercentage = 0.75 ' Set the percentage of memory to free up when the cache size exceeds the limit
		options.ExpirationScanFrequency = TimeSpan.FromMinutes(5) ' Set how often the cache should scan for expired items
	End Sub)
	' Other service configurations...
End Sub
VB   C#

Modify the settings following the specifications of your application.

These instructions will help you configure Microsoft.Extensions. In your ASP.NET Core application, use Caching.Memory. Applications can thus operate more quickly and efficiently by storing and retrieving frequently accessed data in the memory cache.

Getting Started

What is IronPDF?

With the help of the well-known .NET library IronPDF, programmers may generate, edit, and display PDF documents inside .NET applications. Creating PDFs from HTML content, photos, or raw data is just one of the many functions it offers for working with PDFs. Other features include adding text, images, and shapes to pre-existing PDF documents, converting HTML pages to PDFs, and extracting text and images from PDFs.

Below are some features of IronPDF:

  • Creating PDFs from HTML, PNGs, and unprocessed data.
  • Extracting images and text from PDFs.
  • Adding PDF headers, footers, and watermarks.
  • PDF documents with password protection and encryption.
  • Filling out forms and digital signature capabilities.

Install the NuGet Package

In your project, make sure the IronPDF package is installed. The NuGet Package Manager Console can be used to install it:

Install-Package IronPdf

To access the ConfigureServices function, open the Startup.cs file in your ASP.NET Core application. To configure IronPDF, add the following code.

using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
    // Configure IronPDF
    services.AddSingleton<HtmlToPdf>();
    // Other service configurations...
}
using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
    // Configure IronPDF
    services.AddSingleton<HtmlToPdf>();
    // Other service configurations...
}
Imports IronPdf
Public Sub ConfigureServices(ByVal services As IServiceCollection)
	' Configure IronPDF
	services.AddSingleton(Of HtmlToPdf)()
	' Other service configurations...
End Sub
VB   C#

By configuring IronPDF's HtmlToPdf service as a singleton, this code makes sure that the application creates and uses only one instance of HtmlToPdf.

Using Microsoft.Extensions.Caching.Memory with IronPDF

In .NET applications, Microsoft.Extensions.Caching.Memory offers a practical means of storing frequently requested data for quicker retrieval.

This source code and snippet illustrates how to use it fundamentally:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DemoController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        private readonly HtmlToPdf _htmlToPdf;
        private readonly ILogger<DemoController > _logger;
        public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
        {
            _logger = logger;
            _cache = cache;
            _htmlToPdf = htmlToPdf;
        }
        [HttpGet]
        public FileContentResult Generate()
        {
            string fileName = "Sample.pdf";
            var stream = GeneratePdf("Hello IronPDF");
            return new FileContentResult(stream, "application/octet-stream")
            {
                FileDownloadName = fileName
            };
        }
        private byte[] GeneratePdf(string htmlContent)
        {
        // object key
            string cacheKey = "GeneratedPdf";
            if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
            {
                // PDF not found in cache, generate it
                var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
                pdfBytes = pdfDocument.BinaryData;
                // Cache the generated PDF with a sliding expiration of 1 hour
                _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
            }
            return pdfBytes;
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DemoController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        private readonly HtmlToPdf _htmlToPdf;
        private readonly ILogger<DemoController > _logger;
        public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
        {
            _logger = logger;
            _cache = cache;
            _htmlToPdf = htmlToPdf;
        }
        [HttpGet]
        public FileContentResult Generate()
        {
            string fileName = "Sample.pdf";
            var stream = GeneratePdf("Hello IronPDF");
            return new FileContentResult(stream, "application/octet-stream")
            {
                FileDownloadName = fileName
            };
        }
        private byte[] GeneratePdf(string htmlContent)
        {
        // object key
            string cacheKey = "GeneratedPdf";
            if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
            {
                // PDF not found in cache, generate it
                var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
                pdfBytes = pdfDocument.BinaryData;
                // Cache the generated PDF with a sliding expiration of 1 hour
                _cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
            }
            return pdfBytes;
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Caching.Memory
Imports System.Net
Imports System.Net.Http.Headers
Namespace DemoWebApplication.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class DemoController
		Inherits ControllerBase

		Private ReadOnly _cache As IMemoryCache
		Private ReadOnly _htmlToPdf As HtmlToPdf
		Private ReadOnly _logger As ILogger(Of DemoController )
		Public Sub New(ByVal logger As ILogger(Of DemoController ), ByVal cache As IMemoryCache, ByVal htmlToPdf As HtmlToPdf)
			_logger = logger
			_cache = cache
			_htmlToPdf = htmlToPdf
		End Sub
		<HttpGet>
		Public Function Generate() As FileContentResult
			Dim fileName As String = "Sample.pdf"
			Dim stream = GeneratePdf("Hello IronPDF")
			Return New FileContentResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
		End Function
		Private Function GeneratePdf(ByVal htmlContent As String) As Byte()
		' object key
			Dim cacheKey As String = "GeneratedPdf"
			Dim pdfBytes() As Byte
			If Not _cache.TryGetValue(cacheKey, pdfBytes) Then
				' PDF not found in cache, generate it
				Dim pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent)
				pdfBytes = pdfDocument.BinaryData
				' Cache the generated PDF with a sliding expiration of 1 hour
				_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))
			End If
			Return pdfBytes
		End Function
	End Class
End Namespace
VB   C#

We import the namespaces required to work with Microsoft and ASP.NET Microsoft.Extensions.Caching.Memory. We create the DemoController controller, which is derived from ControllerBase. This controller will respond to queries sent over HTTP. An instance of IMemoryCache is injected into the controller's constructor.

To control the lifetime of services, including the memory cache, ASP.NET Core offers dependency injection. With the [HttpGet] property applied, the Generate method is marked to handle HTTP GET requests to the store from the designated route (/Demo). We try to get weather forecast data from the cache inside the Generate function by using the given cache key. If the data cannot be used ASP is located in the cache, we use the Generate function to create fresh weather data.

In a scenario with multiple app servers, make sure to configure distributed caching for consistent cache handling across all servers.

To utilize Microsoft.Extensions, refer to the documentation and sample code provided. Caching.Memory is used to cache data and enhance performance in ASP.NET Core applications. In practice, you can adjust the expiration policies, cache keys, and caching behavior to suit your application's needs. Caching data that is expensive to generate or is often accessed by multiple threads can improve the overall user experience and dramatically reduce response times.

Microsoft.Extensions.Caching.Memory Example (With PDF) in C#: Figure 2 - Example output from the code above

Conclusion

All things considered, Microsoft.Extensions.Caching.Memory can be used to increase the scalability and performance of .NET applications, especially those that are based on the ASP.NET Core framework. Developers can improve user experience, minimize latency, and optimize data access by utilizing in-memory caching. The library provides a flexible and user-friendly API for developing caching strategies targeted to particular application requirements, whether it is for caching reference data, query results, or computed values. You can achieve noticeable speed increases and enhanced application responsiveness by adopting caching best practices and adding Microsoft.Extensions.Caching.Memory into your .NET apps.

Through making use of Microsoft.Extensions' features. With the help of IronPDF for dynamic PDF creation and Caching.Memory for effective data caching, .NET developers can greatly enhance the speed of their apps. This potent combination enables developers to easily design high-performing, scalable, and responsive applications by cutting server load, improving user experience, and eliminating processing overhead.

IronPDF can be purchased at a reasonable price, and acquiring the package includes a lifetime license. The package offers outstanding value since it starts at $749, a single fee for multiple systems. For users with licenses, it offers online engineering help around the clock. For further details about the charge, please visit the website. Visit this website to learn more about items made by Iron Software.

< PREVIOUS
OpenAPI .NET (How It Works For Developers)
NEXT >
Ocelot .NET (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >