Skip to main content

๐Ÿš€Master User Authentication in .NET 8 Web API Email Confirmation, Password Reset, 2FA & Lockout with JWT & Identity๐Ÿ”

Part2️⃣ - Caching | ๐Ÿš€ Mastering Microservices: Using YARP as Your Ultimate API Gateway & Reverse Proxy! ๐Ÿ”—๐Ÿ’ก

 


Memory Cache Service Description

This code provides a robust implementation of an in-memory caching service using the IMemoryCache interface from the Microsoft.Extensions.Caching.Memory namespace. The implementation is divided into an interface and a concrete class to promote abstraction and dependency injection.

IMemoryCacheService Interface

The IMemoryCacheService interface defines the contract for the caching service, ensuring that any implementation of this interface will provide the following methods:

  1. SetCache:

    • Parameters:
      • string key: The unique identifier for the cached item.
      • object value: The object to be stored in the cache.
      • int expirationInSeconds: The time in seconds after which the cached item will expire.
    • Description: This method stores a value in the cache with the specified key and sets an expiration time for the cached item.
  2. GetCache:

    • Parameters:
      • string key: The unique identifier for the cached item.
    • Returns: string
    • Description: This method retrieves the cached value associated with the specified key. If the key does not exist in the cache, it returns null.

MemoryCacheService Class

The MemoryCacheService class provides a concrete implementation of the IMemoryCacheService interface. It uses an instance of IMemoryCache to manage the caching operations. The class is designed to be instantiated through dependency injection, promoting loose coupling and making it easier to test and maintain.

  1. Constructor:

    • Parameters:
      • IMemoryCache memoryCache: An instance of IMemoryCache injected via the constructor.
    • Description: The constructor initializes the MemoryCacheService with an IMemoryCache instance, enabling it to perform caching operations.
  2. GetCache Method:

    • Parameters:
      • string key: The unique identifier for the cached item.
    • Returns: string
    • Description: This method retrieves the cached value associated with the specified key from the IMemoryCache instance. If the key does not exist in the cache, it returns null.
  3. SetCache Method:

    • Parameters:
      • string key: The unique identifier for the cached item.
      • object value: The object to be stored in the cache.
      • int expirationInSeconds: The time in seconds after which the cached item will expire.
    • Description: This method stores the specified value in the cache with the given key and sets the expiration time based on the provided expirationInSeconds parameter. The expiration time is calculated from the current time plus the specified number of seconds.

Benefits

  • Improved Performance: By caching frequently accessed data, the system can reduce the load on backend services and decrease response times for end-users.
  • Scalability: Efficient caching mechanisms help in scaling applications by minimizing redundant data processing and network latency.
  • Flexibility: The use of an interface allows for easy swapping of different caching implementations if needed, enhancing the flexibility and maintainability of the codebase.

Usage

To utilize this caching service, you would typically register the MemoryCacheService in your dependency injection container and then inject it into your controllers or services where caching is required. This setup allows you to efficiently manage cached data, improving the overall performance and responsiveness of your application.


Configuring the YARP Middleware Description

This code sets up in-memory caching for an API gateway using the YARP reverse proxy. It registers the necessary services and configures the middleware to handle caching of responses based on request paths.

Service Registration

  1. AddMemoryCache: Registers the in-memory caching service, enabling the application to store and retrieve cache entries.
  2. AddSingleton: Registers the IMemoryCacheService implementation, MemoryCacheService, as a singleton, ensuring a single instance is used throughout the application's lifetime.

Application Pipeline Configuration

  1. MapReverseProxy: Maps the YARP reverse proxy middleware to the application pipeline, enabling request forwarding to backend services.
  2. Custom Middleware: Adds custom middleware to the proxy pipeline for handling caching:
    • Retrieve Caching Service: The middleware retrieves the IMemoryCacheService instance from the request's service provider.
    • Check Cache: Attempts to get a cached response using the request path as the key.
    • Return Cached Response: If a cached response is found, it sets the response content type to JSON and writes the cached response to the response body.
    • Cache Response: If no cached response is found:
      • Temporarily replaces the response body stream with a memory stream.
      • Calls the next middleware in the pipeline.
      • Reads the response body into a string and caches it with the request path as the key and a 60-second expiration time.
      • Restores the original response body stream and copies the cached response into it.

This setup allows the API gateway to efficiently cache and serve responses, reducing load on backend services and improving response times for clients.

Comments

Popular Posts

Complete Employee Management System | .NET 8 Blazor Wasm & Web API - Perform CRUD, Print, PDF etc..

.NET 8 Clean Architecture with Blazor CRUD, JWT & Role Authorization using Identity & Refresh Token๐Ÿ”ฅ

Employee Management System | .NET 8 Blazor Wasm- Profile & real-time data retrieval. Update 1