Skip to footer content
.NET HELP

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

To construct applications responsively and effectively, optimization methods are frequently needed for .NET applications. Caching is a potent approach that involves temporarily storing frequently requested material in a 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# examples with IronPDF efficiently. In this article, we'll discuss the advantages of caching concerning the IronPDF HTML to PDF Conversion 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 is 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 offering a straightforward yet 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: This influences whether to evict items when the cache fills up. Higher-priority entries have a lower chance of being removed.
  • Post-eviction callback: This allows you to fine-tune the logic for handling data when it has expired. It's especially useful where critical data needs refreshing, 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 to retrieve the string key.
  • This interface is implemented by the CacheEntry class, which offers a practical implementation of these features.

Install and Configure Microsoft.Extensions.Caching.Memory

During application startup, memory is used to configure the cache service inside the ASP.NET Core application's service collection. Below is an ASP.NET Core application with Microsoft.Extensions.Caching.Memory configured:

Install the Required NuGet Package

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

Install-Package Microsoft.Extensions.Caching.Memory

Or we can use the 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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, including size restrictions, cache entry eviction tactics, and cache value expiration regulations. Here 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
$vbLabelText   $csharpLabel

Modify the settings according to the specifications of your application.

These instructions will help you configure Microsoft.Extensions.Caching.Memory in your ASP.NET Core application, allowing it to operate more quickly and efficiently by storing and retrieving frequently accessed data.

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, images, 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
$vbLabelText   $csharpLabel

By configuring IronPDF's HtmlToPdf service as a singleton, this code ensures 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.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
using IronPdf;

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;
using IronPdf;

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
Imports IronPdf

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
$vbLabelText   $csharpLabel

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] attribute applied, the Generate method is marked to handle HTTP GET requests to the store from the designated route (/Demo). We try to get the PDF data from the cache using the given cache key. If the data is not found in the cache, we use the GeneratePdf function to create a new PDF.

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

To utilize Microsoft.Extensions.Caching.Memory, refer to the documentation and sample code provided 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 leveraging the 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 IronPDF Licensing Page. Visit this page about Iron Software to learn more about products made by Iron Software.

Frequently Asked Questions

What is Microsoft.Extensions.Caching.Memory?

Microsoft.Extensions.Caching.Memory is an efficient in-memory object caching solution for .NET applications, allowing frequently accessed data to be stored in memory for quick retrieval. It can be used alongside IronPDF for enhanced performance in PDF-centric applications.

How can you integrate an in-memory cache with a .NET library for PDF operations?

You can integrate an in-memory cache with a .NET library like IronPDF by injecting the IMemoryCache interface into your service class and using it to store and retrieve PDF data for faster access.

What is a .NET library that allows developers to create, edit, and display PDF documents?

IronPDF is a .NET library that allows developers to create, edit, and display PDF documents within .NET applications, offering features like HTML to PDF conversion, text extraction, and more.

What are some key types within Microsoft.Extensions.Caching.Memory?

Key types include IMemoryCache for managing cached entries, MemoryCache for in-memory storage, MemoryCacheEntryOptions for configuring cache item settings, and CacheEntry for representing a single cache entry.

How do you configure services in Startup.cs for caching?

In the ConfigureServices method of Startup.cs, add services.AddMemoryCache() to register the memory cache service within the ASP.NET Core application's service collection. This can be used in conjunction with IronPDF for efficient PDF processing.

What are the benefits of caching in .NET applications?

Caching reduces processing time and server load, leading to improved application performance, enhanced user experience, and reduced latency in .NET applications. This is particularly beneficial when working with PDF documents using libraries like IronPDF.

How can you customize cache behavior in .NET?

You can customize cache behavior by setting cache parameters like size limits, expiration policies, and eviction strategies in the memory cache options. This customization can improve the performance of applications using IronPDF for PDF generation and manipulation.

What are some features of a .NET PDF library?

A .NET PDF library like IronPDF supports creating PDFs from HTML, PNGs, and raw data, extracting images and text from PDFs, adding headers and footers, password protection, encryption, and digital signature capabilities.

How can I purchase a .NET PDF library?

IronPDF can be purchased with a lifetime license starting at a single fee. For more details about pricing, visit the IronPDF Licensing Page.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?

Nuget Passed