푸터 콘텐츠로 바로가기
.NET 도움말

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...
}
$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...
}
$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...
}
$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...
}
$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;
        }
    }
}
$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 $799, 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.

자주 묻는 질문

.NET 애플리케이션에서 Microsoft.Extensions.Caching.Memory의 용도는 무엇인가요?

Microsoft.Extensions.Caching.Memory는 인메모리 개체 캐싱을 제공하여 .NET 애플리케이션의 성능을 향상시키는 데 사용됩니다. 자주 액세스하는 데이터를 메모리에 저장하여 빠르게 검색할 수 있으며, 특히 PDF 작업을 위해 IronPDF와 함께 사용할 때 유용할 수 있습니다.

캐싱을 통해 .NET에서 PDF 처리 성능을 어떻게 향상시킬 수 있나요?

캐싱은 자주 요청되는 PDF 데이터를 메모리에 저장하여 처리 시간과 서버 부하를 줄일 수 있습니다. IronPDF와 같은 라이브러리와 통합하면 더 빠른 PDF 생성 및 조작이 가능하여 전반적인 애플리케이션 속도와 응답성을 향상시킬 수 있습니다.

ASP.NET Core 애플리케이션에서 인메모리 캐싱을 어떻게 구현하나요?

ASP.NET Core에서는 Startup.csConfigureServices 메서드에 services.AddMemoryCache()를 추가하여 인메모리 캐싱을 구현할 수 있습니다. 이렇게 하면 효율적인 PDF 처리 및 데이터 검색을 위해 IronPDF와 원활하게 통합됩니다.

캐싱에서 IMemoryCache의 역할은 무엇인가요?

IMemoryCache는 .NET 애플리케이션에서 캐시 항목을 효과적으로 관리하기 위해 사용되는 인터페이스입니다. IronPDF와 함께 사용하면 개발자가 PDF 데이터를 빠르게 저장하고 검색하여 애플리케이션 성능을 향상시킬 수 있습니다.

.NET에서 캐싱을 위한 일반적인 구성 옵션은 무엇인가요?

일반적인 구성 옵션에는 만료 정책, 크기 제한, MemoryCacheEntryOptions를 사용한 퇴거 전략 설정이 포함됩니다. 이러한 구성은 특히 PDF 처리를 위해 IronPDF를 사용할 때 캐싱 프로세스를 최적화합니다.

개발자는 .NET 애플리케이션에서 동적 PDF를 어떻게 만들 수 있나요?

개발자는 IronPDF를 사용하여 .NET 애플리케이션에서 동적 PDF를 만들 수 있습니다. HTML에서 PDF로의 변환, 머리글 및 바닥글 추가 등을 지원하므로 PDF 생성 및 조작을 위한 다용도 도구입니다.

.NET에서 캐싱과 PDF 생성을 통합하면 어떤 이점이 있나요?

.NET 애플리케이션에서 IronPDF를 사용하여 PDF 생성에 캐싱을 통합하면 속도를 크게 향상시키고 지연 시간을 줄일 수 있습니다. 그 결과 자주 사용하는 데이터에 더 빠르게 액세스할 수 있어 사용자 환경이 개선되고 애플리케이션의 확장성이 향상됩니다.

.NET 애플리케이션의 캐싱 시스템을 어떻게 모니터링하고 개선할 수 있나요?

성능 카운터를 구현하여 .NET 애플리케이션의 캐싱 시스템 효율성을 모니터링할 수 있습니다. 이 모니터링을 통해 최적의 성능을 보장하기 위한 조정 및 개선이 가능하며, 특히 PDF 작업을 위해 IronPDF로 작업할 때 유용합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.