Skip to main content

Angular State Management With NgRx

Introduction:

NgRx framework helps Angular to develop more reactive applications. NgRx provides state management to an application, where data of an application is stored at a single place and then supplied throughout the application where ever needed. Using NgRx if data is updated, all the components consuming that data get updated instantly.

Benefits of using NgRx with Angular application like Serializability, Type Safety, Encapsulation, Testable, and Performance.

Key Features:

NgRx framework key features like

  • Store: A store is a data place where all the application related information stored and supplied to the Angular components on demand.
  • Reducer: A reducer is a pure function based on Actions it returns the new state.
  • Actions: An action expresses an event of an application, that causes a change in the state of the application.
  • Selector: A selector is a pure function that obtains a slice of data from the store.
  • Effects: An Effect is to isolate components from using services(APIs) and with the help actions and reducers change the state of the store.
Note: NgRx store version 8+ using in this sample, there are some new features are added and implementation style was changed from v8+ when compare to v7 and below.

Create An Angular Project:

Let's create a sample to show items in a Bakery Shop. So first create the angular project using Angular CLI commands. Click here for Angular CLI commands.

Install @ngrx/store:

Open the command prompt by taking package.json file in the sample project physical location as a reference path. Now to use NgRx framework run the following NPM command
               "npm install @ngrx/store --save"
Now in a package.json observe as below

Actions: 

NgRx Actions represents the event expression of an application. It represents what to happen and how to happen the changes in an application. Based on Action dispatches NgRx Store or NgRx Effects get triggered.
export interface Action {
    type: string;
}
NgRx Action is a simple interface having only one property 'type', this 'type' property is like a name or identification or role of that particular NgRx Action. Since it is an interface we need to implement it to use it. But Ngrx Store provides the predefined function to create and use NgRx action.
import {createAction} from '@ngrx/store';

export const getStudents = createAction(
    '[Student] load all students'
)
  • Here 'createAction' is a predefined function provided by the NgRx Store and it is an overloaded function. 
  • The parameter passed to 'createAction' is a 'type' property of the action, if we observe from the type property this action will trigger an event to load all students from API or NgRx Store.
  • '[Student]' this just namespace or naming convention to represent the NgRx Action type.

import {createAction ,props} from '@ngrx/store';

export const getNewsByRange = createAction(
    '[News] load news by date values',
    props<{startDate:string, endDate:string}>()
)
  • Here 'createAction' is another overloaded function with two parameters. 
  • 'props<T>()' is a function defined by NgRx Store, this function gives the possibility to pass query parameters of action.
  • In the above action method, it represents the loading of news information with specified date ranges as a query filter to the news data

Create Actions:

Our sample application to show bakery items, let us start code to display cakes in a bakery. Now create folder name as 'store', then create another folder named 'cakes' and now create an action file name as cake.action.ts in the 'store/cakes/' folder.
cakes.action.ts :
import {createAction} from '@ngrx/store';
export const loadCakes = createAction(
    '[Cakes] load'
)
Here action represents to load all cakes.

Reducers:

Reducer is a pure function their goal is like the same output every time for the given input. Reducers take two input params like Action and State. 'State' is just a JSON object which stores the data and based on the action type reducer returns the new state to the angular components. This Reducer gets invoked by the store dispatch which will discuss in later.

import {Action, createReducer, on,createAction} from '@ngrx/store';
const loadSomething = createAction(
    'load'
)
export interface State {
    data:any[]
}

export const initialState: State = {
    data:[]
}

const loadReducer = createReducer(initialState,
    on(loadSomething,state => {
        const newState =state;
        newState.data.push(0);
        return state;
    })
);

export function reducer(state: State| undefined,action :Action){
    return loadReducer(state, action);
}
  • 'State' can be imagined as a database in the serverside language. It is to store and deliver the data on demand.
  • 'initialState' is like default empty state at the time no data exist in the store.
  • Reducer function takes state and action as input params. In version 7 or below inside reducer we wrote code like switch case with return new state, but from NgRx v8+ we returning 'createReducer' function which takes two parameters like state and function. 
  • In 'createReducer' second parameter is an arrow function where we can write logic to create a new state and give it back to the application.
  • The reason we always create a new state and return, due Redux(NgRx framework build on top of Redux) principals that reducers are a pure function that is immutable and only return a new state.

Create a Cake Model and Cake State Model:

Models make coding good by providing 'TypeSafety' to it, so whenever possible where ever needed alway create models. Now in this sample, let us create the folder 'model' and inside add files like 'model.ts' which contains all application-related models and 'store.model.ts' which contains all NgRx Store, related models.

model.ts:
export interface Cake{
    Id:number;
    CakeName:string;
    Image:string;
    Cost:number;
}
store.model.ts:
import {Cake} from './model'
export interface CakeState {
   SuccessMessage:string;
   ErrorMessage:string;
   Data:Cake[]
}

Create Reducer:

Create a file at 'stores/cakes' and name as 'cakes.reducer.ts'

import { Action, createReducer, on } from "@ngrx/store";
import {loadCakes} from './cakes.action';

import { CakeState } from "../../models/stores.model";

export const initialState:CakeState ={
  Data : [],
  SuccessMessage : '',
  ErrorMessage: ''
}

const cakeReducer = createReducer(
    initialState,
    on(loadCakes, state => {
        return {
            ...state
        };
    })
)

export function reducer(state: CakeState | undefined, action: Action){
    return cakeReducer(state, action);
}
  • Here 'initialState' is like default state. 
  • 'cakeReducer' is 'createReducer' function here we taking the first parameter as 'State' and the second parameter is 'on' function provided by NgRxStore. 
  • 'on' function overloaded function here we are taking the first parameter action 'loadCake' and the second parameter is arrow function where the state as input parameter here we can create new state using current state and return the state(later steps we will update this 'cakeReducers' with the different set Actions).

Selectors:

Selectors are also pure functions used to get a slice of data from the NgRx store. Selectors represent query methods. Using selectors it isolates or avoids writing data filtering or data modification code in the angular components.
import {createFeatureSelector, createSelector} from '@ngrx/store'
export interface BookState{
    Id:number,
    Name: string,
}
export interface OrdersState {
    Id:number,
    CustomerName:string
}
export interface AppState{
    books:BookState,
    orders:OrdersState
}

export const selectBooks = createFeatureSelector<appstate,Bookstate>('books');
export const selectOrders = createFeatureSelector<appstate,ordersstate>('orders');

export const selectBookName = createSelector(selectBooks, state => state.Name);
export const selectOrderId = createSelector(selectOrders, state => state.Id);
  • In the above example 'BookState', 'OrderState' represents two different stores. 
  • In general, all the store states are maintained under one state can name as 'AppState'(can be called as the application state).
  • NgRx provides 'createFeatureSelector' it gives a particular state in an application based input parameter. 
  • 'createFeatureSelect' expects the string parameter whose value need to exactly match with 'AppState' property name like 'books' and 'orders'.
  •  Here 'selectBooks' represents 'BookState' and 'selectOrders' represents 'OrderState'. 
  • NgRx provides 'createSelector' gets inside data of an 'State'. Here 'selectBookName' represents a collection of book name and 'selectOrders' represents a collection of order ids.

Create Selectors:

Create a file for selectors at a path '/stores' and name the file as 'store.selectors.ts'

import {createFeatureSelector, createSelector} from '@ngrx/store'
import { CakeState } from "../models/stores.model";
export interface AppState {
    cake:CakeState
}

export const selectCakeState = createFeatureSelector<appstate,cakestate>('cake');

export const selectAllCakes = createSelector(selectCakeSate, state => state.Data);
  • Here we have created 'AppState' which encapsulates all other States in the application. 'selectCakeState' holds the 'CakeState' with the help 'createFeatureSelector'. 'createFeatureSelector' takes 'cake' as input parameter, this 'cake' string should match with property name 'AppState'.
  • 'selectAllCakes' is a state which represents a collection of 'Cake' with the help of 'createSelector' provided by NgRx Store 

Create A Service:

Now in the 'assets' folder add a new file name as cake.json in that file mock some cake items. In real-time we are going to consume API instead of a mock JSON file
Create a service folder as 'app/services' in that add a new file 'cake.service.ts'. It is an injectable service that calls cakes.json file using angular Httpclient.

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import{map} from "rxjs/operators";

@Injectable()
export class CakeService {
  constructor(private http: HttpClient) {}

  get(){
     return this.http.get("./assets/cakes.json").pipe(map(data=> data["AllCakes"]))
  }
}

Effects:

In an Angular Application creates injectable services to consume APIs. We access those services by injecting them into our components to display the data from API. Instead of injecting services into the components we can achieve the same functionality by using NgRx Effects. By using the Effects we can isolate services from components.

Effects are like events that occur out of the application and are not consumed by components directly like we do for services. Effects are triggered based on action dispatched from the store, once the effect gets activated it calls API and pushes the data to the store.
import {Injectable} from '@angular/core';
import {Actions,createEffect, ofType} from '@ngrx/effects';
import {of} from 'rxjs'
import {mergeMap, map, catchError} from 'rxjs/operators'

@Injectable()
export class SomeEffects{
  constructor(private actions$:Actions){

  }

  loadSomething$ = createEffect(() => 
      this.actions$.pipe(
          ofType('[Something] load Something'),
          mergeMap(() => of('In real time here api call observable will be used')
          .pipe(
              map(data => ({type:'[Something] load Something Successfully',payload:data})),
              catchError(() => of({type:'[Something] load Something Failed'}))
          ))
      )
  ) 
}
  • 'createEffect' is provided by the NgRx store to create an effect like 'loadSomething$'. 'createEffect' takes a function as an input parameter, this input parameter function returns observable. 
  • 'Actions' is provided by the NgRx Effects. 'Actions' is an observable type, it gets invoked on every action dispatched from the store in angular components. 
  • 'Actions' are injected into effects services, since it is observable here we listen to the action using 'pipe' operator. 'OfType' in NgRx Effects filters the action by matching the action type  (like '[Something] load Something') with the action type dispatched from the store, if both types of actions match effects goes further execution else effect will be stoped. This says 'OfType' helps to execute the appropriate Effects. 
  • Then listen to the inner observable of API call inside of 'mergeMap' RXJS operators. Finally on the successful execution of inner observable returns observable object of action type and payload data or if inner observable fails returns observable object of an action. This observable result will be available to the NgRx store for changing its state.

Install Effects:

Ngrx shifts effects separate package so run the following command
            npm install @ngrx/effects --save

Create An Effect:

Now add Effects file in 'src/stores/cakes/' and name as 'cakes.effects.ts'

import { Injectable } from "@angular/core";
import { Actions, createEffect, ofType } from "@ngrx/effects";
import { of } from "rxjs";
import { mergeMap, map, catchError } from "rxjs/operators";
import { CakeService } from "../../services/cake.service";

@Injectable()
export class SomeEffects {
  constructor(private actions$: Actions, private cakeService:CakeService) {}

  loadCakes$ = createEffect(() =>
    this.actions$.pipe(
      ofType('[Cakes] load'),
      mergeMap( () => this.cakeService.get()
      .pipe(
          map(data => ({type:'[Cakes] successful cakes load',cakes:data})),
          catchError(eror => of({type:'[Cakes] fails cakes load'}))
      ))
    )
  );
}
  • 'Actions' from NgRx effects and CakeService are injected into this effects service. 
  • 'loadCakes$' creates an effect using 'createEffect()'. 'ofType('[Cakes] load')' it represent this effect only triggered for '[Cakes] load' action. 
  • On successful API call return Observable of the object literal with keys like 'type' and 'cake'  (this 'cakes' name should match with the action props method like props<{cakes: Cake[]}>). On failed API call return Observable of the object literal with key 'type'. This Observable object will be passed to the store based on action types passed in the key 'type' and then the store creates a new state.

Create Actions For API Success And Fail:

In previous steps, we have created the '[Cakes] load' action. Now we need to update the 'cakes.action.ts' file with 2 more actions

export const successCakeLoad = createAction(
    '[Cakes] successful cakes load',
    props<{cakes:Cake[]}>()
);

export const failsCakeLoad = createAction(
    '[Cakes] fails cakes load'
)

Update Reducer To Change Store State Based On API Success Or Fail Actions:

Now update the 'cake.reducer.ts' which changes the state of the store based on the action methods.

import { Action, createReducer, on } from "@ngrx/store";
import * as cakesAction from './cakes.action';

import { CakeState } from "../../models/stores.model";

export const initialState:CakeState ={
  Data : [],
  SuccessMessage : '',
  ErrorMessage: ''
}

const cakeReducer = createReducer(
    initialState,
    on(cakesAction.successCakeLoad,
        (state, {cakes}) => {
            return {
                ...state,
                Data : cakes,
                SuccessMessage : 'Success',
                ErrorMessage:''
            }
        }),
    on(cakesAction.failsCakeLoad,
        state => {
            return {
                ...state,
                Data:[],
                SuccessMessage:'',
                ErrorMessage:'failed'
            }
        })    
)

export function reducer(state: CakeState | undefined, action: Action){
    return cakeReducer(state, action);
}

  • On 'cakeAction.successCakeLoad' action represents API success, here create a new state with the payload from the API and SuccessMessage property update with some success message
  • On 'cakeAction.failsCakeLoad' action represents API fails, here create new state with empty data and ErrorMessage property updated with some error message

Access Data From NgRx Store:

Let save API data to store and access it from the angular component. Now create a new component at 'src/cakes' and name as cakes.component.ts

import {Component, OnInit} from '@angular/core';
import {Store, select} from '@ngrx/store';

import {CakeState} from '../models/stores.model'
import * as cakeActions from '../stores/cakes/cakes.action';
import * as storeSelectors from '../stores/store.selectors';
import {Cake} from '../models/model'

@Component({
    selector:'cakes',
    templateUrl:'cake.component.html'
})
export class CakeComponent implements OnInit {
    allCakes:Cake[];
    constructor(private store:Store<storeSelectors.AppState>){

    }
    ngOnInit(){
        this.store.pipe(select(storeSelectors.selectAllCakes)).subscribe(data => {
            this.allCakes = data;
        });
        this.store.dispatch(cakeActions.loadCakes());
    }
}
  • In the constructor inject store like 'Store<storeSelectors.AppState>', by doing this we have access to the store with all states that are used in the application this happened because store type is 'AppState'.
  • AppState is an application state which holds all other individual stores states. In our application, we created only one state 'CakeState', which resides inside the 'AppState'.
  • In ngOnInit, we dispatch the action 'cakeActions.loadCakes()'. In an application on dispatching an action will automatically trigger all the 'NgRx Effects' get invoked, but the only Effect gets executed which matches the action dispatched. If we recall the above steps we have created NgRx Effect with action name 'loadCakes'.
  • In ngOnInit, we registered a store subscription with the NgRx Selector 'selectAllCakes'. This subscription gets invoked on every update of the store. Herewith 'selecAllCakes' selector going to query all the cakes from the store.
Now create 'cake.component.html' to display  our cakes:
<h1>Cake Bite</h1>

<div class="row">
    <div class="col col-sm-4" *ngFor="let cake of allCakes">
        <div class="card">
            <img src="/assets/{{cake.Image}}" class="card-img-top" alt="">
        </div>
        <div class="card-body">
           <h5 class="card-title">{{cake.CakeName}}</h5>
           <div class="row">
             <div class="col col-sm-6">
                Cost
             </div>
             <div class="col col-sm-6">
                $ {{cake.Cost}}
             </div>
           </div>
        </div>
    </div>
</div>

Update NgRx Store & NgRx Effects Module In AppMoudle:

Final step update NgRx Store and NgRx Effects modules in AppModule file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {StoreModule} from '@ngrx/store';
import {EffectsModule} from '@ngrx/effects';
import {HttpClientModule} from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {CakeComponent} from './cakes/cake.component';
import * as cakeReducer from './stores/cakes/cakes.reducer';
import {CakeEffects} from './stores/cakes/cakes.effect';
import {CakeService} from './services/cake.service';

@NgModule({
  declarations: [
    AppComponent,
    CakeComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    StoreModule.forRoot({cake:cakeReducer.reducer}),
    EffectsModule.forRoot([CakeEffects]),
    AppRoutingModule
  ],
  providers: [CakeService],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • 'StoreModule.forRoot({})' is NgRx Store modules, we need to register all our application reducer function like key-value pair object in the module
  • 'EffectsModule.forRoot([])' is NgRx Effects modules, we need to register all our application effects like an array of objects in the module.

Test Sample Application:

Summary:

A successful sample application was created using NgRx Store. Using the NgRx Store Statemangement of an application becomes a very essay. Since NgRx Effects isolate services from the angular component, it makes angular components very lightweight and logic free. Data sharing between components will become very flexible.

Refer:


Comments

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl