<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1563380748301069004</id><updated>2026-10-08T12:53:59.448+05:30</updated><category term="C#"/><category term="ASP.Net"/><category term="Angular"/><category term="SQL Server"/><category term="Code Snippest"/><category term="Java Script"/><category term="Design Patterns"/><category term="Tips and Tricks"/><category term="Jquery"/><category term=".Net Core"/><category term="Angular Component"/><category term="Behavioral Design Patterns"/><category term="GridView"/><category term="Single Page Application"/><category term="SPA"/><category term="Structural Design Pattern"/><category term=".Net"/><category term="Dependency Injection"/><category term="Linq"/><category term="Angular Directive"/><category term="Caching"/><category term="Creational Design Pattern"/><category term="Database"/><category term="CSS"/><category term="Decorator"/><category term="MVC"/><category term="Microservices"/><category term="Web Api"/><category term=".Net Core Memory Caching"/><category term="Blogging Tips"/><category term="DataTable"/><category term="Mail"/><category term="Microservice Design Patterns"/><category term="RxJs"/><category term="VB.Net"/><category term="Web Service"/><category term="XML"/><category term="ASP.Net MVC Core"/><category term="ASp.Net Controls"/><category term="Angular Pipe"/><category term="Angular Property Binding"/><category term="Angular Routes"/><category term="Angular Template"/><category term="Angular reactive form"/><category term="Angular17"/><category term="Attribute Binding"/><category term="Authentication"/><category term="Backbone.js"/><category term="C# Program"/><category term="Component Commutication"/><category term="Design Pattern"/><category term="Distributed Caching"/><category term="Freshers"/><category term="Google API"/><category term="LINQ to SQL"/><category term="Middleware"/><category term="PDF"/><category term="Reflection"/><category term="Singleton  Pattern"/><category term="Stored Procedure"/><category term="Window Application"/><category term="iTextSharp"/><category term="@Inject"/><category term="@Injectable"/><category term="A gular Providers"/><category term="AI in .NET"/><category term="API Gateway"/><category term="Abstract Design Pattern"/><category term="Adapter Design Pattern"/><category term="Ajax"/><category term="Angular CLI"/><category term="Angular DI"/><category term="Angular Dependency Injection"/><category term="Angular Forms"/><category term="Angular Module"/><category term="Angular Preloading Strategy"/><category term="Angular Providers"/><category term="Angular Resolution Modifier"/><category term="Angular Route Gaurd"/><category term="Angular Routing"/><category term="Angular Service"/><category term="Angular Signals"/><category term="Angular Typed Form"/><category term="Assemblies"/><category term="Autherization"/><category term="Backbone Model"/><category term="Batch Commands"/><category term="Blogger"/><category term="Bridge Design Pattern"/><category term="Builder Design Pattern"/><category term="C"/><category term="Chain of Responsibility Pattern"/><category term="ChatGpt"/><category term="ClaimsIdentity"/><category term="ClaimsPrincipal"/><category term="Collation"/><category term="Command Design Pattern"/><category term="Composite Design Pattern"/><category term="Constructor"/><category term="Consul"/><category term="Content Projection"/><category term="Control Flow"/><category term="Decoratore Design Pattern"/><category term="Defer Block"/><category term="Exception"/><category term="Facade Design Pattern"/><category term="Factory Design Pattern"/><category term="Factory Method Pattern"/><category term="File upload"/><category term="File upload validation"/><category term="FileUpload"/><category term="Flyweight Design Pattern"/><category term="GMail"/><category term="GOF"/><category term="Gangs of Four Design Pattern"/><category term="Generative AI"/><category term="Generic"/><category term="Generic Collection"/><category term="GitHub Models"/><category term="HTML"/><category term="HTTP"/><category term="HybridCaching"/><category term="IL"/><category term="IMemoryCache"/><category term="Identity Management"/><category term="Input and Output"/><category term="Interpreter Design Pattern"/><category term="Iterator Design Pattern"/><category term="JWT Token"/><category term="Json Web Token"/><category term="LIst"/><category term="Linq to DataTable"/><category term="MVC6"/><category term="Mediator Design Pattern"/><category term="Memento Design Pattern"/><category term="Microservice Architecture"/><category term="Model Binding"/><category term="Observer Design Pattern"/><category term="Ocelot Api Gateway"/><category term="Polly"/><category term="Preloading"/><category term="Primary Key"/><category term="Prototype Design Pattern"/><category term="Proxy Design Pattern"/><category term="Query String"/><category term="RAG"/><category term="Rad Control"/><category term="Resolver"/><category term="Response Caching"/><category term="Retrieval Augmented Generation"/><category term="SMTP"/><category term="Service Discovery Pattern"/><category term="Standalone Component"/><category term="State Design Pattern"/><category term="Strategy Design Pattern"/><category term="String Manipulation"/><category term="Structural Directive"/><category term="Template Method Pattern"/><category term="Tiff"/><category term="User Controls"/><category term="User Defined Function"/><category term="Validation"/><category term="Vector Search"/><category term="Views"/><category term="Visitor Pattern"/><category term="Visual Studio"/><category term="Web Application"/><category term="Window Services"/><category term="You Tube"/><category term="ZIp File"/><category term="and Claim"/><title type='text'>Dot Net World</title><subtitle type='html'>C# | Asp.Net | MVC | SQL Server | jQuery | Java Script | Angular | .Net Core | Microservices</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>225</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-250018706147801754</id><published>2026-03-03T21:05:00.001+05:30</published><updated>2026-03-03T21:18:35.983+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net"/><category scheme="http://www.blogger.com/atom/ns#" term="AI in .NET"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Generative AI"/><category scheme="http://www.blogger.com/atom/ns#" term="GitHub Models"/><category scheme="http://www.blogger.com/atom/ns#" term="RAG"/><category scheme="http://www.blogger.com/atom/ns#" term="Retrieval Augmented Generation"/><category scheme="http://www.blogger.com/atom/ns#" term="Vector Search"/><title type='text'>Building a Web Scraping RAG Pipeline in .NET Using GitHub Models</title><content type='html'>&lt;p&gt;Retrieval‑Augmented Generation (RAG) has quickly become one of the most practical ways to build AI systems that work with real‑world data instead of relying only on a model’s training knowledge.&lt;p&gt;
  &lt;p&gt;Most RAG examples today are written in Python and often depend on frameworks like LangChain. While powerful, this leaves a gap for developers working primarily in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;.NET&lt;/a&gt; and &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/c.html&quot; target=&quot;_blank&quot;&gt;C#&lt;/a&gt;.&lt;p&gt;
&lt;p&gt;In this post, I’ll walk through a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;.NET&lt;/a&gt; Console application I built that implements a complete RAG pipeline using GitHub Models for embeddings and chat completion.&lt;/p&gt;
&lt;h2&gt;What This Project Does?&lt;/h2&gt;
&lt;p&gt;At a high level, this application allows you to:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Provide a website URL&lt;/li&gt;
&lt;li&gt;Automatically scrape and clean the page content&lt;/li&gt;
&lt;li&gt;Convert the content into embeddings&lt;/li&gt;
&lt;li&gt;Store embeddings in an in‑memory vector store&lt;/li&gt;
&lt;li&gt;Ask questions about the website&lt;/li&gt;
&lt;li&gt;Get accurate, context‑aware answers generated by an AI model&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All of this runs inside a .NET Console App, making it easy to debug, extend, and later expose as an API.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Architecture Overview&lt;/h2&gt;
&lt;p&gt;The application follows a simple but effective RAG architecture:&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiV0RWkdakjckpDlXYqj9XiCqyiZ23BoF3E9_9X5vPwKyrphCuHL-de8m2X4RDYHULmi0vQxaxE87Nd6FDtTqyAnMRWU-ARoouEvVpU5cW2BPG4DCJm51kwU1ahsgg8DQiRjFRwARmrlqB6ZZcSo7htifdE3zrgeEviz5GVMsV3tn-zLL6nvnps8cEZ_Do/s1208/RagArchOverview.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Project RAG architecture&quot; border=&quot;0&quot; height=&quot;500&quot; data-original-height=&quot;1208&quot; data-original-width=&quot;1024&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiV0RWkdakjckpDlXYqj9XiCqyiZ23BoF3E9_9X5vPwKyrphCuHL-de8m2X4RDYHULmi0vQxaxE87Nd6FDtTqyAnMRWU-ARoouEvVpU5cW2BPG4DCJm51kwU1ahsgg8DQiRjFRwARmrlqB6ZZcSo7htifdE3zrgeEviz5GVMsV3tn-zLL6nvnps8cEZ_Do/s400/RagArchOverview.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p style=&quot;clear: both;&quot;&gt;Each step is implemented as a separate service, making the system easy to test and reuse.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;How the RAG Pipeline Works?&lt;/h2&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;h3&gt;Web Scraping&lt;/h3&gt;
    &lt;p&gt;The application fetches the website HTML and extracts visible content from tags like: p, h1–h6,li, span, div.&lt;/p&gt;
    &lt;p&gt;Script and style tags are removed to reduce noise.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;h3&gt;Text Chunking&lt;/h3&gt;
    &lt;p&gt;The cleaned text is split into overlapping chunks.This improves retrieval accuracy and mirrors how modern RAG systems operate. Example: Chunk size: 300 characters and Overlap: 50 characters&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;h3&gt;Embeddings with GitHub Models&lt;/h3&gt;
    &lt;p&gt;Each chunk is converted into a vector embedding using &lt;b&gt;GitHub Models&lt;/b&gt;, allowing the system to perform semantic similarity searches.&lt;/p&gt;
    &lt;p&gt;The same embedding model is used for:&lt;/p&gt;
    &lt;ul&gt;&lt;li&gt;Website content&lt;/li&gt;
      &lt;li&gt;User questions&lt;/li&gt;&lt;/ul&gt;
    &lt;p&gt;This ensures meaningful vector comparisons.&lt;/p&gt;
  &lt;/li&gt;
   &lt;li&gt;&lt;h3&gt;Vector Similarity Search&lt;/h3&gt;
    &lt;p&gt;When a question is asked:&lt;/p&gt;
    &lt;ul&gt;&lt;li&gt;The query is embedded&lt;/li&gt;
      &lt;li&gt;Cosine similarity is calculated against all stored vectors&lt;/li&gt;
      &lt;li&gt;The &lt;b&gt;top K most relevant chunks&lt;/b&gt; are selected&lt;/li&gt;
     &lt;/ul&gt;
    &lt;p&gt;This acts as the knowledge retrieval step.&lt;/p&gt;
  &lt;/li&gt;
  
  &lt;li&gt;&lt;h3&gt;Prompt Construction&lt;/h3&gt;
    &lt;p&gt;The final prompt sent to the chat model contains:&lt;/p&gt;
    &lt;ul&gt;&lt;li&gt;Retrieved context chunks&lt;/li&gt;
      &lt;li&gt;Conversation history&lt;/li&gt;
      &lt;li&gt;The user’s question&lt;/li&gt;
     &lt;/ul&gt;
    &lt;p&gt;This keeps responses accurate, grounded, and conversational.&lt;/p&gt;
  &lt;/li&gt;
  
  &lt;li&gt;&lt;h3&gt;Chat Completion&lt;/h3&gt;
    &lt;p&gt;The prompt is sent to a &lt;b&gt;GitHub Models chat model&lt;/b&gt;, which generates the final answer. If the context does not contain relevant information, the model is instructed to clearly say so.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Running the Application&lt;/h2&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
dotnet restore
dotnet run
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Console Commands&lt;/h2&gt;
 &lt;ul&gt;
   &lt;li&gt;Enter a website URL to initialize the RAG pipeline&lt;/li&gt;
      &lt;li&gt;Ask questions about the website content&lt;/li&gt;
      &lt;li&gt;Type new to load another website&lt;/li&gt;
   &lt;li&gt;Type quit to exit&lt;/li&gt;
 &lt;/ul&gt;
&lt;p&gt;&lt;b&gt;Check out the full source code on GitHub:&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/WebScrapeRag&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;Memento Design Pattern&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/250018706147801754/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2026/03/building-web-scraping-rag-pipeline-in.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/250018706147801754'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/250018706147801754'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2026/03/building-web-scraping-rag-pipeline-in.html' title='Building a Web Scraping RAG Pipeline in .NET Using GitHub Models'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiV0RWkdakjckpDlXYqj9XiCqyiZ23BoF3E9_9X5vPwKyrphCuHL-de8m2X4RDYHULmi0vQxaxE87Nd6FDtTqyAnMRWU-ARoouEvVpU5cW2BPG4DCJm51kwU1ahsgg8DQiRjFRwARmrlqB6ZZcSo7htifdE3zrgeEviz5GVMsV3tn-zLL6nvnps8cEZ_Do/s72-c/RagArchOverview.png" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-3615665015696084118</id><published>2024-12-16T09:17:00.004+05:30</published><updated>2024-12-16T09:42:25.771+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Component"/><category scheme="http://www.blogger.com/atom/ns#" term="Content Projection"/><title type='text'>Content Projection in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Content Projection in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, content projection is a powerful technique that allows developers to pass content from a parent &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; into a child component, and display it in a specific location within the child &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&#39;s&lt;/a&gt; template. This mechanism enables component reusability and flexibility, making it an essential concept for building modular applications.&lt;/p&gt;
&lt;p&gt;This blog post delves into the concept of content projection, its types, and provides an example to help you understand how to implement it effectively.&lt;/p&gt;
&lt;h2&gt;What is Content Projection?&lt;/h2&gt;
&lt;p&gt;Content projection allows you to project or &quot;transclude&quot; external content into a component’s template. It uses the &lt;b&gt;&amp;lt;ng-content&amp;gt;&lt;/b&gt; directive, which acts as a placeholder in the child component’s template where the content provided by the parent component will be inserted.&lt;/p&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h2&gt;Types of Content Projection&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Single-Slot Content Projection:&lt;/strong&gt;&lt;ul&gt;&lt;li&gt;The simplest form, where one &lt;b&gt;&amp;lt;ng-content&amp;gt;&lt;/b&gt; tag is used in the child component.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Multi-Slot Content Projection:&lt;/strong&gt;&lt;ul&gt;&lt;li&gt;Uses the select attribute to project different types of content into different slots.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Conditional Content Projection:&lt;/strong&gt;&lt;ul&gt;&lt;li&gt;Employs structural directives like &lt;b&gt;*ngIf&lt;/b&gt; to conditionally display projected content.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;Example: Single-Slot Content Projection&lt;/h2&gt;
&lt;p&gt;Let’s start with a basic example to demonstrate single-slot content projection.&lt;/p&gt;
&lt;h3&gt;Step 1: Create a Child Component&lt;/h3&gt;
&lt;p&gt;Create a child component that includes an &amp;lt;ng-content&amp;gt; tag in its template.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// child.component.ts
import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  template: `
    &lt;div class=&quot;child-container&quot;&gt;
      &lt;h2&gt;Child Component&lt;/h2&gt;
      &lt;ng-content&gt;&lt;/ng-content&gt;
    &lt;/div&gt;
  `,
  styles: [
    `.child-container { border: 2px solid #007BFF; padding: 10px; margin: 10px; }`
  ]
})
export class ChildComponent {}
&lt;/pre&gt;
&lt;h3&gt;Step 2: Use the Child Component in a Parent Component&lt;/h3&gt;
&lt;p&gt;Pass custom content from the parent &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; to the child &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// parent.component.ts
import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-parent&#39;,
  template: `
    &lt;div class=&quot;parent-container&quot;&gt;
      &lt;h1&gt;Parent Component&lt;/h1&gt;
      &lt;app-child&gt;
        &lt;p&gt;This is the projected content!&lt;/p&gt;
      &lt;/app-child&gt;
    &lt;/div&gt;
  `,
  styles: [
    `.parent-container { border: 2px solid #28A745; padding: 10px; margin: 10px; }`
  ]
})
export class ParentComponent {}
&lt;/pre&gt;
&lt;h3&gt;Result&lt;/h3&gt;
&lt;p&gt;Output will look like this.&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpSlu0z3EDjMhLt1WrLfNqD4mYhNKUgDEKVkZPTPq2XMYbw1E-ZN_w3O-Kpg85VoAiAzCqph1MoEeUXwItCc9rJmI8EYDw0E4OUAvQuQYW683sLWG3MFWF3N5CV681jtyLEx6kfIx462uB3CeibwsLvVvyGHo_eiW6PSR0x3YIWzn4Zl3ceSS0uoR0ve8/s1600/Screenshot%202024-12-15%20210219.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; data-original-height=&quot;276&quot; data-original-width=&quot;869&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpSlu0z3EDjMhLt1WrLfNqD4mYhNKUgDEKVkZPTPq2XMYbw1E-ZN_w3O-Kpg85VoAiAzCqph1MoEeUXwItCc9rJmI8EYDw0E4OUAvQuQYW683sLWG3MFWF3N5CV681jtyLEx6kfIx462uB3CeibwsLvVvyGHo_eiW6PSR0x3YIWzn4Zl3ceSS0uoR0ve8/s1600/Screenshot%202024-12-15%20210219.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h2&gt;Example: Multi-Slot Content Projection&lt;/h2&gt;
&lt;p&gt;To project multiple slots, use the &lt;b&gt;select&lt;/b&gt; attribute in &lt;b&gt;&amp;lt;ng-content&amp;gt;&lt;/b&gt; tags.&lt;/p&gt;
&lt;h3&gt;Step 1: Update the Child Component Template&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// child.component.ts
@Component({
  selector: &#39;app-child&#39;,
  template: `
    &lt;div class=&quot;child-container&quot;&gt;
      &lt;h2&gt;Child Component&lt;/h2&gt;
      &lt;ng-content select=&quot;[header]&quot;&gt;&lt;/ng-content&gt;
      &lt;ng-content select=&quot;[body]&quot;&gt;&lt;/ng-content&gt;
    &lt;/div&gt;
  `,
  styles: [
    `.child-container { border: 2px solid #007BFF; padding: 10px; margin: 10px; }`
  ]
})
export class ChildComponent {}
&lt;/pre&gt;
&lt;h3&gt;Step 2: Update the Parent Component Template&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// parent.component.ts
@Component({
  selector: &#39;app-parent&#39;,
  template: `
    &lt;div class=&quot;parent-container&quot;&gt;
      &lt;h1&gt;Parent Component&lt;/h1&gt;
      &lt;app-child&gt;
        &lt;div header&gt;This is the header content!&lt;/div&gt;
        &lt;div body&gt;This is the body content!&lt;/div&gt;
      &lt;/app-child&gt;
    &lt;/div&gt;
  `,
  styles: [
    `.parent-container { border: 2px solid #28A745; padding: 10px; margin: 10px; }`
  ]
})
export class ParentComponent {}
&lt;/pre&gt;
&lt;h3&gt;Result&lt;/h3&gt;
&lt;p&gt;The output will display the header and body content in their respective slots within the child &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Benefits of Content Projection&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;span&gt;Enhances reusability by allowing dynamic content insertion.&lt;/span&gt;&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;span&gt;Separates the concerns of structure and content.&lt;/span&gt;&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;span&gt;Reduces redundancy by avoiding repeated component code.&lt;/span&gt;&lt;/p&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Content projection is a fundamental concept in Angular that empowers developers to create reusable and flexible components. By mastering single-slot, multi-slot, and conditional projection, you can build robust and scalable Angular applications. Start experimenting with &lt;b&gt;&amp;lt;ng-content&amp;gt;&lt;/b&gt; in your projects to harness its full potential!&lt;/p&gt;
&lt;p&gt;Find out more about content projection &lt;a href=&quot;https://angular.dev/guide/components/content-projection&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/3615665015696084118/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/content-projection-in-angular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/3615665015696084118'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/3615665015696084118'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/content-projection-in-angular.html' title='Content Projection in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-5327269103849067135</id><published>2024-12-09T07:30:00.001+05:30</published><updated>2024-12-09T07:30:00.225+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Dependency Injection"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular DI"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Resolution Modifier"/><title type='text'>Angular(DI) Resolution Modifiers</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Angular(DI) Resolution Modifiers&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;In Angular, one of its core strengths lies in its &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;Dependency Injection (DI)&lt;/a&gt; system, which ensures that components and services can seamlessly interact. A key feature of this DI system is the use of &lt;b&gt;Resolution Modifiers&lt;/b&gt;. In this blog post, we&#39;ll explore what &lt;b&gt;Resolution Modifiers&lt;/b&gt; are, how they work, and their practical applications in Angular.&lt;/p&gt;
&lt;h2&gt;What Are Resolution Modifiers?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Resolution Modifiers&lt;/b&gt; in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; provide specific instructions to the dependency injection system on how to resolve a dependency. They are used to modify the default behavior of &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;Angular&#39;s DI system&lt;/a&gt;, allowing developers to handle more complex scenarios effectively.&lt;/p&gt;
&lt;p&gt;Angular provides four main resolution modifiers:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;@Optional&lt;/li&gt;&lt;li&gt;@Self&lt;/li&gt;&lt;li&gt;@SkipSelf&lt;/li&gt;&lt;li&gt;@Host&lt;/li&gt;&lt;/ol&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;p&gt;These decorators are applied to constructor parameters in a component or service to control how dependencies are injected.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;@Optional&lt;/h3&gt;
&lt;p&gt;The &lt;b&gt;@Optional&lt;/b&gt; decorator tells Angular that a dependency is optional. If the DI system cannot resolve the dependency, it will inject null instead of throwing an error.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, Optional } from &#39;@angular/core&#39;;
import { SomeService } from &#39;./some.service&#39;;

@Component({
  selector: &#39;app-optional-example&#39;,
  template: &#39;&lt;p&gt;Check the console for details.&lt;/p&gt;&#39;
})
export class OptionalExampleComponent {
  constructor(@Optional() private someService: SomeService) {
    console.log(&#39;Service:&#39;, someService);
  }
}
&lt;/pre&gt;
&lt;strong&gt;When to Use:&lt;/strong&gt;
&lt;ul&gt;&lt;li&gt;Use &lt;b&gt;@Optional&lt;/b&gt; when a dependency is not critical for the component’s functionality.&lt;/li&gt;&lt;li&gt;Ideal for scenarios where a service might or might not be available.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;@Self&lt;/h3&gt;
&lt;p&gt;The &lt;b&gt;@Self&lt;/b&gt; decorator restricts &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;Angular&#39;s DI system&lt;/a&gt; to only look for the dependency in the current injector. If the dependency is not found, Angular will throw an error instead of searching up the injector hierarchy.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, Self } from &#39;@angular/core&#39;;
import { SomeService } from &#39;./some.service&#39;;

@Component({
  selector: &#39;app-self-example&#39;,
  template: &#39;&lt;p&gt;Check the console for details.&lt;/p&gt;&#39;
})
export class SelfExampleComponent {
  constructor(@Self() private someService: SomeService) {
    console.log(&#39;Service:&#39;, someService);
  }
}
&lt;/pre&gt;
&lt;strong&gt;When to Use:&lt;/strong&gt;
&lt;ul&gt;&lt;li&gt;Use &lt;b&gt;@Self&lt;/b&gt; when you want to ensure the dependency comes from the current injector only.&lt;/li&gt;&lt;li&gt;Prevents accidental resolution of dependencies from ancestor injectors.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;@SkipSelf&lt;/h3&gt;
&lt;p&gt;The &lt;b&gt;@SkipSelf&lt;/b&gt; decorator tells Angular to skip the current injector and look for the dependency in ancestor injectors.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, SkipSelf } from &#39;@angular/core&#39;;
import { SomeService } from &#39;./some.service&#39;;

@Component({
  selector: &#39;app-skip-self-example&#39;,
  template: &#39;&lt;p&gt;Check the console for details.&lt;/p&gt;&#39;
})
export class SkipSelfExampleComponent {
  constructor(@SkipSelf() private someService: SomeService) {
    console.log(&#39;Service:&#39;, someService);
  }
}
&lt;/pre&gt;
&lt;strong&gt;When to Use:&lt;/strong&gt;
&lt;ul&gt;&lt;li&gt;Use &lt;b&gt;@SkipSelf&lt;/b&gt; when you explicitly want to avoid resolving a dependency from the current injector.&lt;/li&gt;&lt;li&gt;Useful in hierarchical injector configurations where certain dependencies are defined only at specific levels.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;@Host&lt;/h3&gt;
&lt;p&gt;&lt;b&gt;@Host&lt;/b&gt; instructs Angular to look for the required dependency in the closest component with the requested service in its injector hierarchy. It starts the search from the component where the directive with this decorator is applied.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, SkipSelf } from &#39;@angular/core&#39;;
import { SomeService } from &#39;./some.service&#39;;

@Component({
  selector: &#39;app-skip-self-example&#39;,
  template: &#39;&lt;p&gt;Check the console for details.&lt;/p&gt;&#39;
})
export class SkipSelfExampleComponent {
  constructor(@Host() private someService: SomeService) {
    console.log(&#39;Service:&#39;, someService);
  }
}
&lt;/pre&gt;
&lt;h2&gt;Practical Scenarios&lt;/h2&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;b&gt;Handling Fallbacks with @Optional:&lt;/b&gt; If a feature is only available conditionally, you can use &lt;b&gt;@Optional&lt;/b&gt; to gracefully handle the absence of its service.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Scoped Services with @Self:&lt;/b&gt; When implementing a service that should only exist within a specific component or module, use &lt;b&gt;@Self&lt;/b&gt; to enforce this boundary.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Avoiding Circular Dependencies with @SkipSelf:&lt;/b&gt; In hierarchical dependency setups, &lt;b&gt;@SkipSelf&lt;/b&gt; can help prevent circular dependency issues by bypassing the current injector.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Resolution Modifiers are a powerful tool in Angular&#39;s Dependency Injection system. They give developers fine-grained control over how dependencies are resolved, ensuring greater flexibility and robustness in application design. By understanding and leveraging these modifiers, you can handle complex dependency scenarios with ease.&lt;/p&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/5327269103849067135/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/angulardi-resolution-modifiers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5327269103849067135'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5327269103849067135'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/angulardi-resolution-modifiers.html' title='Angular(DI) Resolution Modifiers'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-4253674969442902682</id><published>2024-12-02T07:30:00.004+05:30</published><updated>2024-12-02T07:30:00.111+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Preloading Strategy"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Routes"/><category scheme="http://www.blogger.com/atom/ns#" term="Preloading"/><title type='text'>Angular Preloading Strategy : Enhancing User Experience and Performance</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Angular Preloading Strategy&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;&lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; offers several features to enhance performance and improve the user experience. One of these features is preloading, a mechanism to load modules in the background after the application has been bootstrapped.At the heart of this feature is the PreloadStrategy, a powerful tool for optimizing Angular applications.&lt;/p&gt;
&lt;p&gt;In this blog post, we’ll explore what PreloadStrategy is, its significance, how it works, and how to customize it to suit your needs.&lt;/p&gt;
&lt;h2&gt;What is PreloadStrategy?&lt;/h2&gt;
&lt;p&gt;In Angular applications, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-lazy-loaded-modules-in.html&quot; target=&quot;_blank&quot;&gt;lazy loading&lt;/a&gt; is commonly used to load modules only when needed, reducing the initial bundle size and improving load time. However, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-lazy-loaded-modules-in.html&quot; target=&quot;_blank&quot;&gt;lazy loading&lt;/a&gt; might cause a delay when users navigate to a route whose module hasn’t been loaded yet. &lt;b&gt;Preloading&lt;/b&gt; bridges this gap by loading &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-lazy-loaded-modules-in.html&quot; target=&quot;_blank&quot;&gt;lazy-loaded modules&lt;/a&gt; in the background after the application is initialized.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;PreloadStrategy&lt;/b&gt; is an &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; interface that defines the strategy for preloading these modules. By default, Angular provides two built-in strategies:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;NoPreloading&lt;/strong&gt;: Disables preloading entirely.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;PreloadAllModules&lt;/strong&gt;: Preloads all lazy-loaded modules as soon as possible.&lt;/li&gt;&lt;/ol&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h2&gt;Why Use Preloading?&lt;/h2&gt;
&lt;p&gt;Preloading enhances user experience by:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Reducing Navigation Latency&lt;/strong&gt;: Modules are preloaded before users navigate to them, making transitions smoother.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Balancing Performance&lt;/strong&gt;: By preloading selectively, you can optimize network usage and avoid unnecessary loads.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;How Does Preloading Work?&lt;/h2&gt;
&lt;p&gt;Angular’s preloading mechanism relies on the router. When defining routes, you specify lazy-loaded modules with the loadChildren property. &lt;b&gt;Preloading&lt;/b&gt; strategies dictate whether these modules should be loaded immediately after the application starts or deferred until navigation.&lt;/p&gt;
&lt;p&gt;Here’s an example of enabling preloading with the &lt;b&gt;PreloadAllModules&lt;/b&gt; strategy:&lt;/p&gt;
&lt;h3&gt;Step 1: Configuring the Router&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { RouterModule, Routes, PreloadAllModules } from &#39;@angular/router&#39;;

const routes: Routes = [
  { path: &#39;&#39;, redirectTo: &#39;home&#39;, pathMatch: &#39;full&#39; },
  { path: &#39;home&#39;, loadChildren: () =&gt; import(&#39;./home/home.module&#39;).then(m =&gt; m.HomeModule) },
  { path: &#39;about&#39;, loadChildren: () =&gt; import(&#39;./about/about.module&#39;).then(m =&gt; m.AboutModule) },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
  exports: [RouterModule]
})
export class AppRoutingModule {}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;Step 2: Including the Router in Your Application&lt;/h3&gt;
&lt;p&gt;Ensure your application’s &lt;b&gt;AppModule&lt;/b&gt; imports the &lt;b&gt;AppRoutingModule&lt;/b&gt;:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { BrowserModule } from &#39;@angular/platform-browser&#39;;
import { AppRoutingModule } from &#39;./app-routing.module&#39;;
import { AppComponent } from &#39;./app.component&#39;;

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule],
  bootstrap: [AppComponent]
})
export class AppModule {}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Customizing PreloadStrategy&lt;/h2&gt;
&lt;p&gt;Sometimes, preloading all modules might not be ideal. You may want to preload specific modules based on conditions like user roles or network bandwidth. For such cases, you can create a custom &lt;b&gt;PreloadStrategy&lt;/b&gt;.&lt;/p&gt;
&lt;h3&gt;Creating a Custom PreloadStrategy&lt;/h3&gt;
&lt;p&gt;A custom strategy involves implementing the &lt;b&gt;PreloadStrategy&lt;/b&gt; interface and overriding the &lt;b&gt;preload&lt;/b&gt; method:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;
import { Route, PreloadingStrategy } from &#39;@angular/router&#39;;
import { Observable, of } from &#39;rxjs&#39;;

@Injectable({ providedIn: &#39;root&#39; })
export class CustomPreloadStrategy implements PreloadingStrategy {
  preload(route: Route, load: () =&gt; Observable&amp;lt;any&amp;gt;): Observable&amp;lt;any&amp;gt; {
    // Check for a custom data property to decide whether to preload
    if (route.data &amp;&amp; route.data[&#39;preload&#39;]) {
      return load();
    }
    return of(null);
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;Using the Custom Strategy&lt;/h3&gt;
&lt;p&gt;To use your custom strategy, configure the router as follows:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@NgModule({
  imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadStrategy })],
  exports: [RouterModule]
})
export class AppRoutingModule {}
&lt;/pre&gt;
&lt;p&gt;And add &lt;b&gt;data&lt;/b&gt; properties to your routes:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
const routes: Routes = [
  { path: &#39;home&#39;, loadChildren: () =&gt; import(&#39;./home/home.module&#39;).then(m =&gt; m.HomeModule), data: { preload: true } },
  { path: &#39;about&#39;, loadChildren: () =&gt; import(&#39;./about/about.module&#39;).then(m =&gt; m.AboutModule), data: { preload: false } },
];
&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Preloading strategies in Angular are essential for balancing application performance and user experience. The default strategies—&lt;b&gt;NoPreloading&lt;/b&gt; and &lt;b&gt;PreloadAllModules&lt;/b&gt;—cover basic needs, but you can tailor preloading behavior by implementing custom strategies. By leveraging preloading effectively, you can create applications that are fast and responsive, delighting your users.&lt;/p&gt;
&lt;p&gt;Find out more about Preloading &lt;a href=&quot;https://angular.dev/api/router/PreloadingStrategy&quot; target=&quot;_blank&quot;&gt;here.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/4253674969442902682/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/angular-preloading-strategy.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4253674969442902682'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4253674969442902682'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/12/angular-preloading-strategy.html' title='Angular Preloading Strategy : Enhancing User Experience and Performance'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-3721996653853168242</id><published>2024-11-29T07:30:00.001+05:30</published><updated>2024-11-29T07:30:00.111+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Routes"/><category scheme="http://www.blogger.com/atom/ns#" term="Resolver"/><title type='text'>Understanding Resolvers in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Resolvers in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;When building &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; applications, one of the common requirements is to fetch data before navigating to a route. For instance, consider a scenario where you want to display a user&#39;s details on a profile page. Instead of loading the route and showing a spinner while fetching data, wouldn&#39;t it be better to resolve the data before entering the route? This is where &lt;b&gt;Angular Resolvers&lt;/b&gt; shine.&lt;/p&gt;
&lt;p&gt;In this post, we&#39;ll explore what resolvers are, why they&#39;re essential, and how to use them effectively in your &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; applications&lt;/p&gt;
&lt;h2&gt;What is a Resolver in Angular?&lt;/h2&gt;
&lt;p&gt;A &lt;b&gt;Resolver&lt;/b&gt; in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; is a service that retrieves data before a route is activated. It ensures that your component is rendered with the required data already available, improving user experience by reducing the time spent waiting for asynchronous calls after the view is loaded.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Resolvers&lt;/b&gt; are part of &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&#39;s&lt;/a&gt; &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/09/route-guards-in-angular.html&quot; target=&quot;_blank&quot;&gt;Route Guards&lt;/a&gt;, which include &lt;b&gt;CanActivate&lt;/b&gt;, &lt;b&gt;CanDeactivate&lt;/b&gt;, &lt;b&gt;CanLoad&lt;/b&gt;, and others. While these guards determine route activation, &lt;b&gt;Resolvers&lt;/b&gt; focus specifically on fetching data.&lt;/p&gt;
&lt;h2&gt;Why Use Resolvers?&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Optimized User Experience&lt;/strong&gt;: By fetching data before rendering, you avoid rendering incomplete views with loading indicators.&lt;/li&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;li&gt;&lt;strong&gt;Centralized Data Logic&lt;/strong&gt;: Resolvers encapsulate data-fetching logic, keeping your components clean and focused on UI concerns.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;: Resolvers allow you to handle errors gracefully and redirect users if data retrieval fails.&lt;/li&gt;&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Implementing a Resolver&lt;/h2&gt;
&lt;p&gt;Here’s a step-by-step guide to creating and using a Resolver in Angular&lt;/p&gt;
&lt;h3&gt;Step 1: Define the Resolver Function&lt;/h3&gt;
&lt;p&gt;Here’s how you can create a resolver using &lt;a href=&quot;https://v17.angular.io/api/router/ResolveFn&quot; target=&quot;_blank&quot;&gt;ResolveFn&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { ResolveFn } from &#39;@angular/router&#39;;
import { inject } from &#39;@angular/core&#39;;
import { UserService } from &#39;./user.service&#39;;

export const userResolver: ResolveFn&amp;lt;User&amp;gt; = (route, state) =&gt; {
  const userService = inject(UserService);
  const userId = route.paramMap.get(&#39;id&#39;);
  return userService.getUserById(userId!);
};
&lt;/pre&gt;
&lt;p&gt;In the above code we have:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Dependency Injection&lt;/strong&gt;: The &lt;b&gt;inject()&lt;/b&gt; function provides access to the &lt;b&gt;UserService&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Route Parameters&lt;/strong&gt;: Use &lt;b&gt;route.paramMap.get(&#39;id&#39;)&lt;/b&gt; to fetch dynamic route parameters.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Return Value&lt;/strong&gt;: Return an observable, promise, or synchronous value. Angular will wait for the observable to resolve before activating the route.&lt;/li&gt;&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;Step 2: Configure the Route&lt;/h3&gt;
&lt;p&gt;Add the resolver to the desired route in the &lt;b&gt;RouterModule&lt;/b&gt; configuration.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Routes } from &#39;@angular/router&#39;;
import { UserComponent } from &#39;./user.component&#39;;
import { userResolver } from &#39;./user.resolver&#39;;

const routes: Routes = [
  {
    path: &#39;user/:id&#39;,
    component: UserComponent,
    resolve: { userData: userResolver },
  },
];
&lt;/pre&gt;
&lt;p&gt;Here, the &lt;b&gt;resolve&lt;/b&gt; property maps the &lt;b&gt;resolver (userResolver)&lt;/b&gt; to a key &lt;b&gt;(userData)&lt;/b&gt; that can be accessed in the component.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;Step 3: Access Resolved Data in the Component&lt;/h3&gt;
&lt;p&gt;We can access the resolved data in &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; by using &lt;b&gt;ActivatedRoute’s&lt;/b&gt; data property.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { ActivatedRoute } from &#39;@angular/router&#39;;

@Component({
  selector: &#39;app-user&#39;,
  template: `&lt;h1&gt;User Details&lt;/h1&gt;
             &lt;pre&gt;{{ user | json }}&lt;/pre&gt;`,
})
export class UserComponent implements OnInit {
  user: User | undefined;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.user = this.route.snapshot.data[&#39;userData&#39;];
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Resolvers in Angular are a powerful tool for managing data preloading and improving user experience. By combining resolvers with Angular&#39;s routing and lazy-loading capabilities, you can build robust, user-friendly applications.&lt;/p&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/3721996653853168242/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/understanding-resolvers-in-angular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/3721996653853168242'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/3721996653853168242'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/understanding-resolvers-in-angular.html' title='Understanding Resolvers in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-6212775124048203121</id><published>2024-11-20T17:30:00.009+05:30</published><updated>2024-11-20T17:30:00.112+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net Core"/><category scheme="http://www.blogger.com/atom/ns#" term="and Claim"/><category scheme="http://www.blogger.com/atom/ns#" term="Authentication"/><category scheme="http://www.blogger.com/atom/ns#" term="Autherization"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="ClaimsIdentity"/><category scheme="http://www.blogger.com/atom/ns#" term="ClaimsPrincipal"/><category scheme="http://www.blogger.com/atom/ns#" term="Identity Management"/><title type='text'>Understanding ClaimsPrincipal, ClaimsIdentity, and Claim in C#</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Understanding ClaimsPrincipal, ClaimsIdentity, and Claim in C#&quot; border=&quot;0&quot; data-original-height=&quot;174&quot; data-original-width=&quot;200&quot; height=&quot;150&quot; width=&quot;150&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;When developing applications that require user authentication and authorization, managing user identities and their associated information securely is essential. In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/c.html&quot; target=&quot;_blank&quot;&gt;C#&lt;/a&gt;, the classes &lt;b&gt;ClaimsPrincipal&lt;/b&gt;, &lt;b&gt;ClaimsIdentity&lt;/b&gt;, and &lt;b&gt;Claim&lt;/b&gt; in the &lt;b&gt;System.Security.Claims&lt;/b&gt; namespace provide a flexible and extensible way to manage user identity data in a claims-based manner.&lt;/p&gt;
&lt;p&gt;In this post, we&#39;ll explore the concepts of &lt;b&gt;ClaimsPrincipal&lt;/b&gt;, &lt;b&gt;ClaimsIdentity&lt;/b&gt;, and &lt;b&gt;Claim&lt;/b&gt; in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/c.html&quot; target=&quot;_blank&quot;&gt;C#&lt;/a&gt;, and see how they work together to represent and manage user identity information.&lt;/p&gt;
&lt;h2&gt;Understanding Claims-Based Identity&lt;/h2&gt;
&lt;p&gt;Before diving into the classes, it’s helpful to understand the concept of claims-based identity. A claim is a statement about a user that provides information about who they are, what they can do, or other relevant attributes. Examples of claims include:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;The user&#39;s email address&lt;/li&gt;&lt;li&gt;A role or permission level (like &quot;Admin&quot; or &quot;User&quot;)&lt;/li&gt;&lt;li&gt;The user&#39;s age or country of residence&lt;/li&gt;&lt;/ul&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;p&gt;A claims-based approach to identity allows you to store these attributes about users and use them to authorize access to various resources or features within an application.&lt;/p&gt;
&lt;h2&gt;Claim, ClaimsIdentity, and ClaimsPrincipal&lt;/h2&gt;
&lt;h3&gt;Claim&lt;/h3&gt;
&lt;p&gt;A &lt;b&gt;Claim&lt;/b&gt; is the smallest unit in claims-based identity management. Each claim represents a single piece of information about a user. In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/aspnet.html&quot; target=&quot;_blank&quot;&gt;.NET&lt;/a&gt;, a &lt;b&gt;Claim&lt;/b&gt; object consists of:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Type&lt;/strong&gt;: A string identifier for the claim, such as &lt;b&gt;ClaimTypes.Email&lt;/b&gt;, &lt;b&gt;ClaimTypes.Role&lt;/b&gt;, or custom identifiers.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Value&lt;/strong&gt;: The data associated with the claim type, such as an email address or role.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;ValueType&lt;/strong&gt;: Optional, indicating the data type of the claim (e.g., &lt;b&gt;string&lt;/b&gt;, &lt;b&gt;boolean&lt;/b&gt;).&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Issuer&lt;/strong&gt;: Optional, indicating which system provided the claim.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Here’s how you might create a Claim object in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/c.html&quot; target=&quot;_blank&quot;&gt;C#&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using System.Security.Claims;

// Create a claim representing the user&#39;s email address
var emailClaim = new Claim(ClaimTypes.Email, &quot;user@example.com&quot;);
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;ClaimsIdentity&lt;/h3&gt;
&lt;p&gt;A &lt;b&gt;ClaimsIdentity&lt;/b&gt; represents a user identity and acts as a container for a set of claims. Each identity can have multiple claims, making it a way to associate a collection of claims with a single user. Additionally, an identity can be labeled with an authentication type, which indicates how the user was authenticated (e.g., &quot;Forms&quot;, &quot;OAuth&quot;).&lt;/p&gt;
&lt;p&gt;Creating a &lt;b&gt;ClaimsIdentity&lt;/b&gt; and adding claims to it is straightforward:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// Create a ClaimsIdentity for the user, with a set of claims
var claims = new List&amp;lt;Claim&amp;gt;
{
    new Claim(ClaimTypes.Name, &quot;John Doe&quot;),
    new Claim(ClaimTypes.Email, &quot;johndoe@example.com&quot;),
    new Claim(ClaimTypes.Role, &quot;Admin&quot;)
};

var identity = new ClaimsIdentity(claims, &quot;CustomAuthType&quot;);
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;ClaimsPrincipal&lt;/h3&gt;
&lt;p&gt;A &lt;b&gt;ClaimsPrincipal&lt;/b&gt; is the top-level class that represents the user’s identity as a whole. It can contain one or more ClaimsIdentity instances, which means a user could have multiple identities in different contexts (e.g., a business identity and a personal identity).&lt;/p&gt;
&lt;p&gt;ClaimsPrincipal is particularly useful for authorization as it provides methods for querying claims, checking roles, and retrieving the user’s identity data across different authentication mechanisms.&lt;/p&gt;
&lt;p&gt;Creating a &lt;b&gt;ClaimsPrincipal&lt;/b&gt; from a &lt;b&gt;ClaimsIdentity&lt;/b&gt; looks like this:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
var principal = new ClaimsPrincipal(identity);
&lt;/pre&gt;
&lt;p&gt;You can access claims in the &lt;b&gt;ClaimsPrincipal&lt;/b&gt; like so:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
var email = principal.FindFirst(ClaimTypes.Email)?.Value;
var isAdmin = principal.IsInRole(&quot;Admin&quot;);
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;How Claims-Based Identity Works in ASP.NET Core&lt;/h2&gt;
&lt;p&gt;In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt;, claims-based identity is tightly integrated into the authentication and authorization framework. When a user logs in, &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt; creates a &lt;b&gt;ClaimsPrincipal&lt;/b&gt; for that user, populated with claims provided by the authentication mechanism (e.g., from a database, external login provider, or token). You can configure custom claims by adding them to the &lt;b&gt;ClaimsPrincipal&lt;/b&gt; as part of your authentication process.&lt;/p&gt;
&lt;h3&gt;Example: Adding Claims to the User in ASP.NET Core&lt;/h3&gt;
&lt;p&gt;Here’s an example of adding custom claims after the user authenticates in ASP.NET Core:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
public async Task&amp;lt;IActionResult&gt;&amp;gt; Login(string username, string password)
{
    if (ValidateUser(username, password))
    {
        var claims = new List&amp;lt;Claim&amp;gt;
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(&quot;Department&quot;, &quot;IT&quot;),
            new Claim(ClaimTypes.Role, &quot;Admin&quot;)
        };

        var claimsIdentity = new ClaimsIdentity(claims, &quot;CustomAuthType&quot;);
        var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        await HttpContext.SignInAsync(claimsPrincipal);

        return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
    }

    return View(&quot;LoginFailed&quot;);
}
&lt;/pre&gt;
&lt;p&gt;In this example, if &lt;b&gt;ValidateUser&lt;/b&gt; confirms the user credentials, we create a new &lt;b&gt;ClaimsPrincipal&lt;/b&gt; with relevant claims, and call &lt;b&gt;SignInAsync&lt;/b&gt; to persist the user’s authentication status.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Advantages of Using Claims-Based Identity&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Flexibility&lt;/strong&gt;: Claims allow you to attach arbitrary data to users, enabling complex authorization logic.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Simplified Role Management&lt;/strong&gt;: Roles are just one type of claim, so authorization logic can be extended beyond simple roles.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Federation-Friendly&lt;/strong&gt;: Claims are essential when integrating with external identity providers (e.g., Google, Microsoft) because they facilitate exchanging user identity information securely.&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;ClaimsPrincipal&lt;/b&gt;, &lt;b&gt;ClaimsIdentity&lt;/b&gt;, and &lt;b&gt;Claim&lt;/b&gt; classes in C# provide a powerful and flexible way to manage user identities and authorization. By adopting a claims-based approach to identity, you can create applications that are secure, adaptable, and easy to integrate with external identity providers.&lt;/p&gt;

Find out more -
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.security.claims.claimsprincipal?view=net-8.0&quot; target=&quot;_blank&quot;&gt;Claims Principle&lt;/a&gt;&lt;/li&gt;
   &lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.security.claims.claimsidentity?view=net-8.0&quot; target=&quot;_blank&quot;&gt;Claims Indentity&lt;/a&gt;&lt;/li&gt;
   &lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.security.claims.claim?view=net-8.0&quot; target=&quot;_blank&quot;&gt;Claims&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/6212775124048203121/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/claimsprincipal-claimsidentity-claim-in-csharp.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/6212775124048203121'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/6212775124048203121'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/claimsprincipal-claimsidentity-claim-in-csharp.html' title='Understanding ClaimsPrincipal, ClaimsIdentity, and Claim in C#'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s72-c/DotNetCore.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-2653947781264473259</id><published>2024-11-13T09:30:00.002+05:30</published><updated>2024-11-13T09:30:00.117+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net Core"/><category scheme="http://www.blogger.com/atom/ns#" term="Caching"/><category scheme="http://www.blogger.com/atom/ns#" term="HybridCaching"/><title type='text'>Exploring HybridCache in .Net 9</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;HybridCaching in .NET Core&quot; border=&quot;0&quot; data-original-height=&quot;174&quot; data-original-width=&quot;200&quot; height=&quot;150&quot; width=&quot;150&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;As &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt; continues to evolve, with the release of &lt;b&gt;.NET 9&lt;/b&gt;, a new caching mechanism called &lt;b&gt;HybridCache&lt;/b&gt; has been introduced, offering a blend of &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/12/imemorycache-in-net-core-with-example.html&quot; target=&quot;_blank&quot;&gt;in-memory&lt;/a&gt; and &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/12/distributed-caching-in-net-core-with.html&quot; target=&quot;_blank&quot;&gt;distributed caching&lt;/a&gt; to address the limitations of traditional caching methods.&lt;/p&gt;

&lt;h2&gt;What is HybridCache?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;HybridCache&lt;/b&gt; is a caching library designed to combine the best features of in-memory caching (L1) and distributed caching (L2). This dual-layer approach helps mitigate common issues like cache stampedes and race conditions, ensuring a more robust and efficient caching strategy.&lt;/p&gt;

&lt;h2&gt;Key Features of HybridCache&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;
&lt;b&gt;Stampede Protection:&lt;/b&gt; Prevents multiple concurrent requests from overwhelming the cache by ensuring only one request fetches the data while others wait for the result.&lt;/li&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
 &lt;li&gt;&lt;b&gt;Multi-Tier Caching:&lt;/b&gt; Utilizes both in-memory (L1) and distributed (L2) caches, balancing speed and storage capacity. &lt;/li&gt;
 &lt;li&gt;&lt;b&gt;Configurable Serialization:&lt;/b&gt; Offers flexibility in how data is serialized and deserialized, catering to various application needs. &lt;/li&gt;
 &lt;li&gt;&lt;b&gt;Tag-Based Eviction:&lt;/b&gt; Allows for more granular control over cache invalidation, improving cache management.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Setting Up HybridCache&lt;/h2&gt;
&lt;p&gt;To get started with HybridCache in your ASP.NET Core application, follow these steps:&lt;/p&gt;

&lt;h3&gt;Install the Package&lt;/h3&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
dotnet add package Microsoft.Extensions.Caching.Hybrid 
&lt;/pre&gt;
&lt;h3&gt;Register the Service&lt;/h3&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHybridCache();
&lt;/pre&gt;
&lt;h3&gt;Using HybridCache&lt;/h3&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
public class SomeService
{
    private readonly HybridCache _cache;

    public SomeService(HybridCache cache)
    {
        _cache = cache;
    }

    public async Task&amp;lt;string&amp;gt; GetSomeInfoAsync(string name, int id, CancellationToken token = default)
    {
        return await _cache.GetOrCreateAsync(
            $&quot;CacheKey&quot;,
            async cancel =&gt; await GetDataFromTheSourceAsync(name, id, cancel),
            cancellationToken: token
        );
    }

    private async Task&amp;lt;string&amp;gt; GetDataFromTheSourceAsync(string name, int id, CancellationToken token)
    {
        // Simulate data retrieval
        return $&quot;{name}-{id}&quot;;
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Benefits of HybridCache&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Improved Performance:&lt;/b&gt; By leveraging both &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/12/imemorycache-in-net-core-with-example.html&quot; target=&quot;_blank&quot;&gt;in-memory&lt;/a&gt; and &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/12/distributed-caching-in-net-core-with.html&quot; target=&quot;_blank&quot;&gt;distributed caches&lt;/a&gt;, &lt;b&gt;HybridCache&lt;/b&gt; reduces latency and enhances data retrieval speed.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Enhanced Scalability:&lt;/b&gt; The dual-layer caching system allows applications to scale more efficiently, handling larger volumes of data without compromising performance.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Simplified API:&lt;/b&gt; HybridCache provides a unified API for both in-process and out-of-process caching, reducing complexity for developers.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;HybridCache&lt;/b&gt; in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;.NET Core&lt;/a&gt; represents a significant advancement in caching technology, offering a powerful and flexible solution for modern web applications. By combining the strengths of in-memory and distributed caching, it ensures optimal performance, scalability, and reliability.&lt;/p&gt;
&lt;p&gt;&lt;i&gt;For more detailed information and advanced configuration options, refer to the &lt;a href=&quot;https://learn.microsoft.com/en-us/aspnet/core/performance/caching/hybrid?view=aspnetcore-9.0&quot; target=&quot;_blank&quot;&gt;official documentation&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/2653947781264473259/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/exploring-hybridcache-in-net-9.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/2653947781264473259'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/2653947781264473259'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/exploring-hybridcache-in-net-9.html' title='Exploring HybridCache in .Net 9'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s72-c/DotNetCore.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-7505683902024961905</id><published>2024-11-12T07:30:00.003+05:30</published><updated>2024-11-12T07:30:00.221+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net Core"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Polly"/><title type='text'>Polly in .NET Core: A Guide to Resilience and Fault Handling</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinTWGzHDCRUXtewkGUejGhBMbmWWz5oI6vK-6586ocD1fVI8DSjVmIvXVcZsVJbNlcUzDnoMbFleK_eKl-32wV6zaC27h91PmUANLLA1TFBqO7CQ6W7VzKf95-DA_Nww2cqZJE5SN-vqhc53v4sKt-y0zTTVgJ_vXYfxExC5ulT7XOpKgl0QhYarKxCXM/s1600/Polly-Logo.png&quot; style=&quot;display: block; padding: 0 1em 0 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;Polly in .NET Core&quot; border=&quot;0&quot; data-original-height=&quot;128&quot; data-original-width=&quot;128&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinTWGzHDCRUXtewkGUejGhBMbmWWz5oI6vK-6586ocD1fVI8DSjVmIvXVcZsVJbNlcUzDnoMbFleK_eKl-32wV6zaC27h91PmUANLLA1TFBqO7CQ6W7VzKf95-DA_Nww2cqZJE5SN-vqhc53v4sKt-y0zTTVgJ_vXYfxExC5ulT7XOpKgl0QhYarKxCXM/s1600/Polly-Logo.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;&lt;b&gt;Polly&lt;/b&gt; is a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;.NET&lt;/a&gt; library that provides a framework for handling transient faults in an application. It allows developers to implement retry policies, circuit breakers, timeouts, and other fault-handling patterns in a clean, composable, and declarative way. In this post, we&#39;ll explore what Polly is, why it’s valuable, and how to use it in .NET Core applications to build resilient, fault-tolerant solutions.&lt;/p&gt;
&lt;h2&gt;What is Polly?&lt;/h2&gt;
&lt;p&gt;Polly is an open-source library that enables you to build fault-handling and resilience logic into your applications. It helps you manage faults and unexpected scenarios by providing a range of resilience policies. Polly works seamlessly with .NET Core and can be used across HTTP clients, database calls, message queues, and more. Here are the key policies Polly supports:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Retry&lt;/strong&gt;: Retry a failed operation multiple times before giving up.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Circuit Breaker&lt;/strong&gt;: Stop calling a failing service temporarily to give it time to recover.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Timeout&lt;/strong&gt;: Fail if an operation takes longer than a specified time.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Fallback&lt;/strong&gt;: Provide an alternative response or behavior when an operation fails.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Bulkhead Isolation&lt;/strong&gt;: Limit concurrent executions to avoid resource exhaustion.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Cache&lt;/strong&gt;: Cache responses to avoid repeated calls for the same result.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;By combining these policies, Polly enables you to create robust and customizable resilience strategies tailored to your application’s needs.&lt;/p&gt;
&lt;h2&gt;Why Use Polly?&lt;/h2&gt;
&lt;p&gt;In any distributed application, you’ll inevitably encounter issues like network instability, service unavailability, or rate limiting. Polly allows you to handle these scenarios without excessive code and helps:&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Improve User Experience&lt;/strong&gt;: Users will experience fewer errors and smoother interactions if transient faults are handled gracefully.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Enhance Reliability&lt;/strong&gt;: Redundant attempts (like retries) increase the likelihood of success when services experience intermittent failures.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Manage System Load&lt;/strong&gt;: Circuit breakers and bulkhead isolation help to prevent overwhelming dependent services and your application.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;By using Polly in .NET Core applications, you get a consistent and reliable way to manage resilience, even as your system scales and complexity grows.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Getting Started with Polly in .NET Core&lt;/h2&gt;
&lt;p&gt;To get started, install Polly through NuGet:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
dotnet add package Polly
&lt;/pre&gt;
&lt;p&gt;Polly integrates well with the &lt;a href=&quot;&quot;&gt;HttpClientFactory&lt;b&gt;&lt;/b&gt;&lt;/a&gt; in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;.NET Core&lt;/a&gt;, which simplifies managing HTTP requests and supports resilient communication between services. Here’s a look at how to apply Polly with &lt;a href=&quot;&quot;&gt;HttpClientFactory&lt;b&gt;&lt;/b&gt;&lt;/a&gt;.
&lt;/p&gt;
&lt;h3&gt;Example: Using Polly with HttpClientFactory in .NET Core&lt;/h3&gt;
&lt;p&gt;The &lt;b&gt;IHttpClientFactory&lt;/b&gt; offers a way to register and configure &lt;b&gt;HttpClient&lt;/b&gt; instances, and it easily integrates Polly policies for fault tolerance.&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Define Resilience Policies&lt;/strong&gt;: Set up retry and circuit breaker policies.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Configure HttpClient&lt;/strong&gt;: Apply these policies to &lt;code&gt;HttpClient&lt;/code&gt;.&lt;/li&gt;&lt;/ol&gt;
&lt;strong&gt;Step 1: Define Resilience Policies&lt;/strong&gt;
&lt;p&gt;In your &lt;b&gt;Startup.cs&lt;/b&gt; or &lt;b&gt;Program.cs&lt;/b&gt; (for minimal APIs), configure Polly policies:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using Polly;
using Polly.Extensions.Http;
using System.Net.Http;

// Retry policy for transient errors
var retryPolicy = HttpPolicyExtensions
    .HandleTransientHttpError() // Handles 5xx errors and network failures
    .OrResult(msg =&gt; msg.StatusCode == HttpStatusCode.TooManyRequests) // Additional handling for 429
    .WaitAndRetryAsync(3, retryAttempt =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

// Circuit breaker policy to prevent hammering a failing service
var circuitBreakerPolicy = HttpPolicyExtensions
    .HandleTransientHttpError()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
&lt;/pre&gt;
&lt;p&gt;These policies set up a retry mechanism with exponential backoff and a circuit breaker to stop calls when repeated failures are detected.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;strong&gt;Step 2: Configure HttpClient with Polly Policies&lt;/strong&gt;
&lt;p&gt;Register &lt;b&gt;HttpClient&lt;/b&gt; in the dependency injection container, applying the Polly policies:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
services.AddHttpClient(&quot;MyResilientClient&quot;, client =&gt;
{
    client.BaseAddress = new Uri(&quot;https://example.api.com/&quot;);
})
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(circuitBreakerPolicy);
&lt;/pre&gt;
&lt;p&gt;Now, when &lt;b&gt;MyResilientClient&lt;/b&gt; is injected into services or controllers, it will automatically use the defined retry and circuit breaker policies.&lt;/p&gt;
&lt;strong&gt;Step 3: Use the Configured HttpClient&lt;/strong&gt;
&lt;p&gt;Inject and use the configured &lt;b&gt;HttpClient&lt;/b&gt; with the resilience policies:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
public class MyService
{
    private readonly HttpClient _httpClient;

    public MyService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient(&quot;MyResilientClient&quot;);
    }

    public async Task&amp;lt;string&amp;gt; GetDataAsync()
    {
        var response = await _httpClient.GetAsync(&quot;/data&quot;);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}
&lt;/pre&gt;
&lt;p&gt;With this setup, &lt;b&gt;GetDataAsync&lt;/b&gt; will retry failed requests automatically up to three times and break the circuit if there are multiple failures within a short timeframe.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Polly in .NET Core is a powerful tool for building resilient and fault-tolerant applications. By using Polly’s declarative syntax, you can easily create custom resilience policies like retries, circuit breakers, and timeouts.&lt;/p&gt;
&lt;p&gt;Find out more about Polly- &lt;a href=&quot;https://www.pollydocs.org/&quot; target=&quot;_blank&quot;&gt;Meet Polly: The .NET resilience library&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/7505683902024961905/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/polly-in-net-core-guide-to-resilience.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/7505683902024961905'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/7505683902024961905'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/polly-in-net-core-guide-to-resilience.html' title='Polly in .NET Core: A Guide to Resilience and Fault Handling'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinTWGzHDCRUXtewkGUejGhBMbmWWz5oI6vK-6586ocD1fVI8DSjVmIvXVcZsVJbNlcUzDnoMbFleK_eKl-32wV6zaC27h91PmUANLLA1TFBqO7CQ6W7VzKf95-DA_Nww2cqZJE5SN-vqhc53v4sKt-y0zTTVgJ_vXYfxExC5ulT7XOpKgl0QhYarKxCXM/s72-c/Polly-Logo.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-5257321873844318784</id><published>2024-11-11T07:30:00.013+05:30</published><updated>2024-11-11T07:30:00.317+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net Core"/><category scheme="http://www.blogger.com/atom/ns#" term="Authentication"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Json Web Token"/><category scheme="http://www.blogger.com/atom/ns#" term="JWT Token"/><title type='text'>Implementing JWT Authentication in .NET Core</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;JWT Authentication in .NET Core&quot; border=&quot;0&quot; data-original-height=&quot;174&quot; data-original-width=&quot;200&quot; height=&quot;150&quot; width=&quot;150&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s1600/DotNetCore.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;JWT (JSON Web Token) is a popular way to implement secure authentication in modern web applications. It provides a lightweight and stateless mechanism to authenticate users, ensuring secure data transfer. In this blog post, we’ll explore how to implement JWT authentication in a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/c.html&quot; target=&quot;_blank&quot;&gt;C#&lt;/a&gt; &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt; application with a step-by-step example.&lt;/p&gt;
&lt;h2&gt;What is JWT?&lt;/h2&gt;
&lt;p&gt;A &lt;b&gt;JWT&lt;/b&gt; is a token that is used to securely transmit information between two parties (client and server). It is digitally signed, ensuring that the data it contains can be trusted. JWT consists of three parts:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Header&lt;/strong&gt;: Specifies the algorithm used to generate the signature, typically HMAC SHA256 or RSA.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Payload&lt;/strong&gt;: Contains the claims or the data being transmitted (such as user ID, roles, etc.).&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Signature&lt;/strong&gt;: Ensures that the token hasn’t been tampered with.&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;The general structure looks like this:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVzZXIwMSIsIm5iZiI6MTczMTIxMDQ4OCwiZXhwIjoxNzMxMjExNjg4LCJpYXQiOjE3MzEyMTA0ODh9.2adOgvFCgF4FfzwWS3VbT-AOUvXvwwMmI76HrdTXFW4
&lt;/pre&gt;
&lt;h2&gt;Why JWT?&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Stateless&lt;/strong&gt;: No need to store sessions on the server.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Scalable&lt;/strong&gt;: The server doesn’t need to store or retrieve session information.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Cross-domain&lt;/strong&gt;: JWT can be easily used across different domains, making it ideal for distributed applications like microservices.&lt;/li&gt;&lt;/ul&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Implementing JWT in C# ASP.NET Core&lt;/h2&gt;
&lt;p&gt;Lets&#39; build a simple &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt; Web Api and implement JWT Authentication. In this demo project we will have three projects-&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;JWTAuthentication.WebApi&lt;/strong&gt;: This will be Api in which we will have two endpoints, one to Authenticate the user and return JWT Token. Another endpoint will be secure which will return data only for valid tokens.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;JwtAuthentication.Services&lt;/strong&gt;:This will be our servcie layer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;JWTAuthentication.TokenManager&lt;/strong&gt;:This will be class library where we will implement JWT token generation.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Lets start the implementation-&lt;/p&gt;
&lt;h3&gt;Setting Up the Project&lt;/h3&gt;
&lt;ol&gt;&lt;li&gt;Open Visual Studio and create a new &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt; project &lt;b&gt;JWTAuthentication.WebApi&lt;/b&gt;.&lt;/li&gt;
  &lt;li&gt;Add a class library in this project name &lt;b&gt;JwtAuthentication.Services&lt;/b&gt;&lt;/li&gt;
  &lt;li&gt;Add another class library in this project name &lt;b&gt;JwtAuthentication.TokenManager&lt;/b&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;h3&gt;JWTAuthentication.TokenManager Project&lt;/h3&gt;
&lt;ol&gt;
  &lt;li&gt;Install the required NuGet packages in JWTAuthentication.TokenManager Project
    &lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
    &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;Add a class file &lt;b&gt;JwtExtension.cs&lt;/b&gt; and Create a extension method for Registering and configure the JWT Authentication.
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    public static IServiceCollection AddCustomJwtAuthentication(this IServiceCollection services)
    {
    services.AddAuthentication(option =&gt;
    {
        option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(x =&gt;
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = false;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8
                .GetBytes(JWTTokenManager.JWT_Secret)
            ),
            ValidateIssuer = false,
            ValidateAudience = false,
            ClockSkew = TimeSpan.Zero
        };
    });
    return services;
}
    &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;Add a class file &lt;b&gt;JWTTokenManager.cs&lt;/b&gt; and add the below code.
  &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
  public class JWTTokenManager
  {
      public static string JWT_Secret = &quot;Your Secret Key&quot;;
      private static int JWT_TOKEN_VALIADITY_MIN = 20;
      public string GenerateJwtToken(string userName)
      {
          var claims = new List&amp;lt;Claim&amp;gt;
          {
              new Claim(ClaimTypes.Name, userName),
          };
          var key = Encoding.ASCII.GetBytes(JWT_Secret);
          var tokenHandler = new JwtSecurityTokenHandler();
          var tokenDescriptor = new SecurityTokenDescriptor
          {
              Subject = new ClaimsIdentity(claims),
              Expires = DateTime.UtcNow.AddMinutes(JWT_TOKEN_VALIADITY_MIN),
              SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
          };
          var token = tokenHandler.CreateToken(tokenDescriptor);
          return tokenHandler.WriteToken(token);
      }
  }
    &lt;/pre&gt;
    &lt;p&gt;In the above code , you have created a method to generate the JWT Token when a user successfully logs in.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;JwtAuthentication.Services Project&lt;/h3&gt;
&lt;ol&gt;
  &lt;li&gt;Add &lt;b&gt;JWTAuthentication.TokenManager&lt;/b&gt; as reference in JwtAuthentication.Services Project. In this project we will verify the user based on user name and password and on successfull verofication, we will call JWT token creation method which we have implemented in  &lt;b&gt;JWTAuthentication.TokenManager&lt;/b&gt; project&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Models-&lt;/b&gt;Add below class files in this project-AuthenticateRequest.cs, AuthenticateResponse.cs,UserAccount.cs
  &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
  //AuthenticateRequest.cs
  public class AuthenticateRequest
  {
      [Required]
      public string Username { get; set; }

      [Required]
      public string Password { get; set; }
  }
  //AuthenticateResponse.cs
  public class AuthenticateResponse
  {       
      public string Username { get; set; }
      public string Token { get; set; }
  }
  //UserAccount
  public class UserAccount
  {
      [JsonIgnore]
      public string UserName { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }

      [JsonIgnore]
      public string Password { get; set; }
  }
  &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;Add file &lt;b&gt;UserServiceExtensions.cs&lt;/b&gt;. In this file we will create a extension method of &lt;b&gt;IServiceCollection&lt;/b&gt; and add the dependencies-
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
  public static IServiceCollection AddUserServiceDepedencies(this IServiceCollection services) 
  {
      services.AddSingleton^lt;JWTTokenManager&amp;gt;();
      services.AddSingleton&amp;lt;IUserService, UserService&amp;gt;();
      return services;
  }
    &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;Add file &lt;b&gt;UserService.cs&lt;/b&gt; and copy pase the below code-
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
 public interface IUserService
 {
     AuthenticateResponse? Authenticate(AuthenticateRequest model);
     IEnumerable&amp;lt;UserAccount&amp;gt; GetAll();
 }
 public class UserService : IUserService
 {
     // users hardcoded for simplicity, store in a db with hashed passwords in production applications
     private List&amp;lt;UserAccount&amp;gt; _users = new List&amp;lt;UserAccount&amp;gt;
     {
         new UserAccount { FirstName = &quot;Test&quot;, LastName = &quot;User&quot;, UserName = &quot;user01&quot;, Password = &quot;user01&quot; },
         new UserAccount { FirstName = &quot;Test1&quot;, LastName = &quot;User&quot;, UserName = &quot;user02&quot;, Password = &quot;user02&quot; }
     };
     private readonly JWTTokenManager _jwtTokenManager;
     public UserService(JWTTokenManager jwtTokenManager)
     {
         _jwtTokenManager = jwtTokenManager;
     }
     public AuthenticateResponse? Authenticate(AuthenticateRequest model)
     {
         var user = _users.SingleOrDefault(x =&gt; x.UserName == model.Username &amp;&amp; x.Password == model.Password);

         // return null if user not found
         if (user == null) return null;

         // authentication successful so generate jwt token
         var token = _jwtTokenManager.GenerateJwtToken(user.UserName);

         return new AuthenticateResponse { Token = token, Username = user.UserName };
     }
     public IEnumerable&amp;lt;UserAccount&amp;gt; GetAll()
     {
         return _users;
     }

 }
    &lt;/pre&gt;
    &lt;p&gt;Here, we have &lt;b&gt;Authenticate&lt;/b&gt; method to validate the user by username and password.On successfull validation, we are calling &lt;b&gt;GenerateJwtToken&lt;/b&gt; method to generate the new JWT Token&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;JWTAuthentication.WebApi&lt;/h3&gt;
&lt;ol&gt;
  &lt;li&gt;Add &lt;b&gt;JWTAuthentication.TokenManager&lt;/b&gt; and &lt;b&gt;JwtAuthentication.Services&lt;/b&gt; as reference.&lt;/li&gt;
  &lt;li&gt;Modify the Program.cs file to configure the JWT authentication. Add the following to enable JWT authentication
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    builder.Services.AddCustomJwtAuthentication();
	builder.Services.AddAuthorization();
	builder.Services.AddUserServiceDepedencies();
	builder.Services.AddControllers();
    &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;Add authentication middleware-
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    // Enable Authentication and Authorization
    app.UseAuthentication();
	app.UseAuthorization();
    &lt;/pre&gt;
    &lt;p&gt;&lt;b&gt;Program.cs&lt;/b&gt; file will look like this-&lt;/p&gt;
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    using JWTAuthentication.TokenManager.Extensions;
    using JwtAuthentication.Services.Extensions;

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddCustomJwtAuthentication();
    builder.Services.AddAuthorization();
    builder.Services.AddUserServiceDepedencies();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services.AddControllers();


    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
  &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Creating a Authenticate Endpoint&lt;/b&gt; :In your controller, create an action that logs in the user and returns a token.
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    [HttpPost(&quot;authenticate&quot;)]
    public IActionResult Authenticate(AuthenticateRequest model)
    {
        var response = _userService.Authenticate(model);

        if (response == null)
            return BadRequest(new { message = &quot;Username or password is incorrect&quot; });

        return Ok(response);
    }
    &lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Securing API Endpoints&lt;/b&gt; :Now that we have JWT authentication set up, let’s secure an API endpoint. Add the [Authorize] attribute to a controller action that you want to protect
    &lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    [Authorize]
    [HttpGet]
    public IActionResult GetAll()
    {
        var users = _userService.GetAll();
        return Ok(users);
    }
    &lt;/pre&gt;
    &lt;p&gt;This ensures that the GetSecureData method can only be accessed by users who have a valid JWT token.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;Testing the API&lt;/h3&gt;
&lt;p&gt;You can test your API using a tool like &lt;b&gt;Postman&lt;/b&gt; or &lt;b&gt;cURL&lt;/b&gt;.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;First, make a POST request to your authenticate endpoint in this case &lt;b&gt;/api/User/authenticate&lt;/b&gt; with the following JSON in the body:
    &lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    {
    	&quot;username&quot;: &quot;user01&quot;,
        &quot;password&quot;: &quot;user01&quot;
    }
    &lt;/pre&gt;
    &lt;p&gt;You should receive a JWT token in the response.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;Use this token in the &lt;b&gt;Authorization&lt;/b&gt; header for subsequent requests to the secure endpoint.
    &lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
    Authorization: Bearer &amp;lt;your-token-here&amp;gt;
    &lt;/pre&gt;
    &lt;p&gt;Making a &lt;b&gt;GET&lt;/b&gt; request to &lt;b&gt;/api/User&lt;/b&gt; with the token should return the protected data.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The full source code is available here:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/dotnet-core-jwt-authentication-api&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;JWT authentication is a robust and stateless method for securing your ASP.NET Core applications. By following this guide, you now have a basic implementation of JWT authentication in a C# Web API. This approach not only improves security but also simplifies scalability by reducing the need for server-side session management.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;


</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/5257321873844318784/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/jwt-authentication-in-net-core.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5257321873844318784'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5257321873844318784'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/jwt-authentication-in-net-core.html' title='Implementing JWT Authentication in .NET Core'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVD3TF3RQv38zsOu2ely7yHSnwY26cuWHsZM31bExSa8f-A2-bMwU2YFHegTkbh7ICfYEfrt2UOtw7DMLAtYS9_lSJJKfGKLX_lLjASbdAg4X8W4BlQniwxFZ839qD-lwvIyjZVE45lWEc9s0syZpQn5vHXjEwxdfOKykW1630iaSBmPGwg0gmMrYEo7Y/s72-c/DotNetCore.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-8260482370524729803</id><published>2024-11-04T17:30:00.001+05:30</published><updated>2024-11-04T17:30:00.112+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Forms"/><title type='text'>Forms in Angular - A Comprehensive Guide to Building Reactive and Template-Driven Forms</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Forms in angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;Forms are a fundamental part of any web application, enabling users to interact with the app, provide information, and submit data. In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, forms can be implemented using two main approaches: &lt;b&gt;Template-driven&lt;/b&gt; and &lt;b&gt;Reactive&lt;/b&gt; forms. Each approach has unique benefits, so understanding how to use them effectively can elevate your &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; app development.&lt;/p&gt;
&lt;p style=&quot;clear: both;&quot;&gt;In this post, we&#39;ll dive into the following:&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Template-driven forms&lt;/li&gt;&lt;li&gt;Reactive forms&lt;/li&gt;&lt;li&gt;Form validation&lt;/li&gt;&lt;li&gt;Comparing the two approaches&lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;1. Template-Driven Forms&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Template-driven&lt;/b&gt; forms in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; rely heavily on Angular&#39;s two-way data binding. They’re built directly in the HTML template using directives like &lt;b&gt;ngModel&lt;/b&gt;. &lt;b&gt;Template-driven forms&lt;/b&gt; are ideal for simpler forms and are particularly helpful when you don’t need to programmatically control form behavior.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h3&gt;Setting Up a Template-Driven Form&lt;/h3&gt;
&lt;p&gt;To start with a template-driven form, you’ll first need to import the &lt;b&gt;FormsModule&lt;/b&gt; in your &lt;b&gt;AppModule&lt;/b&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { FormsModule } from &#39;@angular/forms&#39;;

@NgModule({
  imports: [FormsModule],
})
export class AppModule {}
&lt;/pre&gt;
&lt;h3&gt;Building a Simple Registration Form&lt;/h3&gt;
&lt;pre class=&quot;brush:html;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
&amp;lt;form #registerForm=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit(registerForm)&quot;&amp;gt;
  &amp;lt;label for=&quot;username&quot;&amp;gt;Username:&amp;lt;/label&amp;gt;
  &amp;lt;input type=&quot;text&quot; id=&quot;username&quot; name=&quot;username&quot; ngModel required&amp;gt;

  &amp;lt;label for=&quot;email&quot;&amp;gt;Email:&amp;lt;/label&amp;gt;
  &amp;lt;input type=&quot;email&quot; id=&quot;email&quot; name=&quot;email&quot; ngModel required email&amp;gt;

  &amp;lt;label for=&quot;password&quot;&amp;gt;Password:&amp;lt;/label&amp;gt;
  &amp;lt;input type=&quot;password&quot; id=&quot;password&quot; name=&quot;password&quot; ngModel required minlength=&quot;6&quot;&amp;gt;

  &amp;lt;button type=&quot;submit&quot; [disabled]=&quot;registerForm.invalid&quot;&amp;gt;Register&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Here’s a breakdown:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;ngModel:&lt;/b&gt; Binds the input elements to the model.&lt;/li&gt;&lt;li&gt;&lt;b&gt;#registerForm=&quot;ngForm&quot;:&lt;/b&gt; Creates a local reference for the form.&lt;/li&gt;&lt;li&gt;&lt;b&gt;ngSubmit:&lt;/b&gt; Binds the form submission to a method in your component.&lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;Handling Form Data in the Component&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-register&#39;,
  templateUrl: &#39;./register.component.html&#39;
})
export class RegisterComponent {
  onSubmit(form: any) {
    console.log(&#39;Form Data:&#39;, form.value);
  }
}
&lt;/pre&gt;
&lt;p&gt;With &lt;b&gt;template-driven forms&lt;/b&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; automatically handles the form instance for you, which is beneficial for simple use cases.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;2. Reactive Forms&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Reactive forms&lt;/b&gt; provide a more programmatic approach to building forms and give you more control over validation, value changes, and error management. Unlike &lt;b&gt;template-driven&lt;/b&gt; forms, &lt;b&gt;reactive&lt;/b&gt; forms rely on explicit form control objects within the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; class.&lt;/p&gt;
&lt;h3&gt;Setting Up a Reactive Form&lt;/h3&gt;
&lt;p&gt;To use reactive forms, you’ll need to import &lt;b&gt;ReactiveFormsModule&lt;/b&gt; in your &lt;b&gt;AppModule&lt;/b&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { ReactiveFormsModule } from &#39;@angular/forms&#39;;

@NgModule({
  imports: [ReactiveFormsModule],
})
export class AppModule {}
&lt;/pre&gt;
&lt;h3&gt;Building a Reactive Login Form&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { FormBuilder, FormGroup, Validators } from &#39;@angular/forms&#39;;

@Component({
  selector: &#39;app-login&#39;,
  templateUrl: &#39;./login.component.html&#39;
})
export class LoginComponent implements OnInit {
  loginForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.loginForm = this.fb.group({
      email: [&#39;&#39;, [Validators.required, Validators.email]],
      password: [&#39;&#39;, [Validators.required, Validators.minLength(6)]],
    });
  }

  onSubmit(): void {
    if (this.loginForm.valid) {
      console.log(&#39;Form Data:&#39;, this.loginForm.value);
    }
  }
}
&lt;/pre&gt;
&lt;h3&gt;HTML Template for Reactive Form&lt;/h3&gt;
&lt;pre class=&quot;brush:html;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
&amp;lt;form [formGroup]=&quot;loginForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&amp;gt;
  &amp;lt;label for=&quot;email&quot;&amp;gt;Email:&amp;lt;/label&amp;gt;
  &amp;lt;input type=&quot;email&quot; id=&quot;email&quot; formControlName=&quot;email&quot;&amp;gt;

  &amp;lt;label for=&quot;password&quot;&amp;gt;Password:&amp;lt;/label&amp;gt;
  &amp;lt;input type=&quot;password&quot; id=&quot;password&quot; formControlName=&quot;password&quot;&amp;gt;

  &amp;lt;button type=&quot;submit&quot; [disabled]=&quot;loginForm.invalid&quot;&amp;gt;Login&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/pre&gt;
&lt;p&gt;In this example:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;b&gt;FormGroup&lt;/b&gt; defines the structure of the form.&lt;/li&gt;&lt;li&gt;&lt;b&gt;formControlName&lt;/b&gt; links form controls to the component class.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;3. Form Validation&lt;/h2&gt;
&lt;p&gt;Angular provides built-in validators such as &lt;b&gt;Validators.required&lt;/b&gt;, &lt;b&gt;Validators.email&lt;/b&gt;, and &lt;b&gt;Validators.minLength&lt;/b&gt; etc. that can be used in both form types. For custom validation, you can create validator functions to enforce specific business rules.&lt;/p&gt;
&lt;h3&gt;Adding Custom Validation&lt;/h3&gt;
&lt;p&gt;In a reactive form, custom validators are easily applied within the &lt;b&gt;FormBuilder&lt;/b&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
function strongPassword(control: FormControl) {
  const hasNumber = /\d/.test(control.value);
  const hasUppercase = /[A-Z]/.test(control.value);
  const isValid = hasNumber &amp;&amp; hasUppercase;
  return isValid ? null : { strongPassword: true };
}
&lt;/pre&gt;
&lt;p&gt;To apply it, add the validator to a control:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
this.loginForm = this.fb.group({
  password: [&#39;&#39;, [Validators.required, strongPassword]],
});
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;4. Comparing Template-Driven and Reactive Forms&lt;/h3&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzN62mc_xqiZNRtw5nMqtf-0grocFmscMq4lH7zl6gCe6L3aBOui-eZP9R2sg4dYivamB85CEXHYnmafKbGTdaHMldq4559zNb7U5AK63NdqOvlHklnmxLti7LRUxuE3wKNfA0Qybq8_hduQHXyP2KXRx42L8p29Mrb5CMOrY_H_nc-kvV4l3iwAr3GDI/s936/Screenshot%202024-11-01%20224248.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;Template-Driven and Reactive Forms Comparision&quot; border=&quot;0&quot; width=&quot;700&quot; data-original-height=&quot;264&quot; data-original-width=&quot;936&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzN62mc_xqiZNRtw5nMqtf-0grocFmscMq4lH7zl6gCe6L3aBOui-eZP9R2sg4dYivamB85CEXHYnmafKbGTdaHMldq4559zNb7U5AK63NdqOvlHklnmxLti7LRUxuE3wKNfA0Qybq8_hduQHXyP2KXRx42L8p29Mrb5CMOrY_H_nc-kvV4l3iwAr3GDI/s400/Screenshot%202024-11-01%20224248.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Angular forms, whether template-driven or reactive, offer powerful ways to collect and validate user input. While template-driven forms work well for simple forms, reactive forms provide robust tools for more complex scenarios. Understanding both approaches and choosing the right one for your app’s needs will greatly improve the development process.&lt;/p&gt;
&lt;p&gt;Start with the basics and practice building forms using both methods to gain confidence in handling Angular forms in real-world applications.&lt;/p&gt;
Find out more: &lt;a href=&quot;https://angular.dev/guide/forms&quot; target=&quot;_blank&quot;&gt;Angular Forms&lt;/a&gt;
&lt;p&gt;Happy larning!! 😊&lt;/p&gt;

</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/8260482370524729803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/angular-forms.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8260482370524729803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8260482370524729803'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/angular-forms.html' title='Forms in Angular - A Comprehensive Guide to Building Reactive and Template-Driven Forms'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-8466638099251269342</id><published>2024-11-01T16:30:00.004+05:30</published><updated>2024-11-01T16:30:00.109+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Signals"/><title type='text'>Angular Signals : A Practical Guide with Examples</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Angular Signals&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;&lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular 17&lt;/a&gt; recently introduced the concept of &lt;b&gt;Signals&lt;/b&gt; to improve reactivity and simplify state management. &lt;b&gt;Signals&lt;/b&gt; allow &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; applications to handle state changes in a more predictable, efficient, and declarative way. This blog will cover what &lt;b&gt;Signals&lt;/b&gt; are, why they matter, and how to use them with practical examples.&lt;/p&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;What are Signals?&lt;/h2&gt;
&lt;p&gt;In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, a &lt;b&gt;Signal&lt;/b&gt; is a reactive primitive that provides a new approach to managing and responding to state changes. With &lt;b&gt;Signals&lt;/b&gt;, you can track changes to specific data points (variables or objects), allowing the app to automatically react when the data changes without needing complex change detection.&lt;/p&gt;
&lt;h2&gt;Why Use Signals?&lt;/h2&gt;
&lt;p&gt;Signals offer several benefits:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Predictable reactivity&lt;/strong&gt;: Signals enable precise control over when a component updates, leading to more predictable behavior.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Improved performance&lt;/strong&gt;: With Signals, Angular avoids unnecessary re-renders by updating only the affected parts.&lt;/li&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;li&gt;&lt;strong&gt;Simplified state management&lt;/strong&gt;: Signals are easy to understand and integrate with Angular’s Dependency Injection, making state management simpler and more scalable.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Creating and Using Signals in Angular&lt;/h2&gt;
&lt;p&gt;Angular Signals can be defined using the &lt;b&gt;signal&lt;/b&gt; function in Angular 16 and above. Let’s walk through an example where we’ll create a simple counter component using Signals.&lt;/p&gt;
&lt;h3&gt;1. Setting Up the Counter Component&lt;/h3&gt;
&lt;p&gt;First, create a new Angular component:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
ng generate component Counter
&lt;/pre&gt;
&lt;h3&gt;2. Import Signals into the Component&lt;/h3&gt;
&lt;p&gt;Import &lt;b&gt;signal&lt;/b&gt;, &lt;b&gt;computed&lt;/b&gt;, and &lt;b&gt;effect&lt;/b&gt; from &lt;b&gt;@angular/core&lt;/b&gt;. These functions allow us to create reactive data and computed states in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, signal, computed, effect } from &#39;@angular/core&#39;;
&lt;/pre&gt;
&lt;h3&gt;3. Define the Counter Component with Signals&lt;/h3&gt;
&lt;p&gt;In your &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; file &lt;b&gt;(counter.component.ts)&lt;/b&gt;, create a signal for the counter state and add methods to increment and decrement its value.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Component({
  selector: &#39;app-counter&#39;,
  templateUrl: &#39;./counter.component.html&#39;,
  styleUrls: [&#39;./counter.component.css&#39;]
})
export class CounterComponent {
  // Define a signal for the counter
  counter = signal(0);

  // Create a computed signal to double the counter value
  doubledCounter = computed(() =&gt; this.counter() * 2);

  // Define methods to increment and decrement the counter
  increment() {
    this.counter.update(value =&gt; value + 1);
  }

  decrement() {
    this.counter.update(value =&gt; value - 1);
  }

  // Set up an effect to log counter changes
  constructor() {
    effect(() =&gt; {
      console.log(&quot;Counter value changed:&quot;, this.counter());
    });
  }
}
&lt;/pre&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;signal(0)&lt;/strong&gt;: Initializes the counter with a value of 0.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;computed(() =&amp;gt; this.counter() * 2)&lt;/strong&gt;: Creates a computed signal that automatically updates when the counter changes.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;effect&lt;/strong&gt;: Logs counter updates to the console whenever the counter’s value changes.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;4. Updating the Component Template&lt;/h3&gt;
&lt;p&gt;Open the &lt;b&gt;counter.component.html&lt;/b&gt; file and add buttons to control the counter. Display both the counter value and the computed doubled counter value.&lt;/p&gt;
&lt;pre class=&quot;brush:html;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
&amp;lt;div&amp;gt;
  &amp;lt;h1&amp;gt;Angular Signals Counter&amp;lt;/h1&amp;gt;
  &amp;lt;p&amp;gt;Counter: {{ counter() }}&amp;lt;/p&amp;gt;
  &amp;lt;p&amp;gt;Doubled Counter: {{ doubledCounter() }}&amp;lt;/p&amp;gt;

  &amp;lt;button (click)=&quot;increment()&quot;&amp;gt;Increment&amp;lt;/button&amp;gt;
  &amp;lt;button (click)=&quot;decrement()&quot;&amp;gt;Decrement&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;{{ counter() }}&lt;/strong&gt;: This syntax retrieves the current value of the counter signal.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;{{ doubledCounter() }}&lt;/strong&gt;: Shows the computed value of counter * 2.&lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;5. Testing the Component&lt;/h3&gt;
&lt;p&gt;Run your Angular application using:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
ng serve
&lt;/pre&gt;
&lt;p&gt;Open your browser, and navigate to &lt;b&gt;http://localhost:4200&lt;/b&gt;. You should see the counter with its initial value, along with buttons to increment and decrement. Every time you click the buttons, the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; updates in real time, and the effect logs the change in the console.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Advanced Example: Using Signals for Form Validation&lt;/h2&gt;
&lt;p&gt;Let’s extend this concept to form validation. In this example, we’ll create a form with a text field and use a computed signal to enable or disable the submit button based on validation.&lt;/p&gt;
&lt;h3&gt;1. Create the Form Component&lt;/h3&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
ng generate component Form
&lt;/pre&gt;
&lt;h3&gt;2. Define Signals for Form State&lt;/h3&gt;
&lt;p&gt;Inside the &lt;b&gt;form.component.ts&lt;/b&gt;, create signals to hold the input value and a computed signal for validation.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, signal, computed } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-form&#39;,
  templateUrl: &#39;./form.component.html&#39;,
  styleUrls: [&#39;./form.component.css&#39;]
})
export class FormComponent {
  // Signal to hold form input
  inputText = signal(&#39;&#39;);

  // Computed signal to check if input is valid
  isInputValid = computed(() =&gt; this.inputText().length &gt;= 3);

  // Update the input text
  updateInputText(value: string) {
    this.inputText.set(value);
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;3. Update the Template with Form Controls&lt;/h3&gt;
&lt;p&gt;In &lt;b&gt;form.component.html&lt;/b&gt;, add a text input and a submit button that is enabled only when the input is valid.&lt;/p&gt;
&lt;pre class=&quot;brush:html;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
&amp;lt;div&amp;gt;
  &amp;lt;h1&amp;gt;Form with Angular Signals&amp;lt;/h1&amp;gt;
  &amp;lt;input
    type=&quot;text&quot;
    placeholder=&quot;Enter at least 3 characters&quot;
    [value]=&quot;inputText()&quot;
    (input)=&quot;updateInputText($event.target.value)&quot;
  /&amp;gt;

  &amp;lt;button [disabled]=&quot;!isInputValid()&quot;&amp;gt;Submit&amp;lt;/button&amp;gt;
  &amp;lt;p *ngIf=&quot;!isInputValid()&quot;&amp;gt;Input must be at least 3 characters.&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;[disabled]=&quot;!isInputValid()&quot;&lt;/strong&gt;: Disables the submit button unless isInputValid is true.&lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;4. Testing the Form Component&lt;/h3&gt;
&lt;p&gt;With this setup, the submit button will enable only when the input text has at least three characters. This demonstrates how Signals can help manage form validation logic simply and effectively.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Using &lt;b&gt;Signals&lt;/b&gt; in Angular can make your code more reactive, efficient, and easier to manage. They work well for basic state management and can be scaled up for more complex applications. By using Signals, &lt;b&gt;computed&lt;/b&gt; values, and &lt;b&gt;effects&lt;/b&gt;, Angular apps become more predictable and performant.&lt;/p&gt;
&lt;p&gt;Find out more: &lt;a href=&quot;https://angular.dev/guide/signals/&quot; target=&quot;_blank&quot;&gt;Angular Signals&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy learning!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/8466638099251269342/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/angular-signals-with-example.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8466638099251269342'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8466638099251269342'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/11/angular-signals-with-example.html' title='Angular Signals : A Practical Guide with Examples'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-968758156126943904</id><published>2024-10-28T06:03:00.014+05:30</published><updated>2024-11-11T02:04:29.483+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Consul"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservice Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="Service Discovery Pattern"/><title type='text'>Service Discovery in Microservices with C# and .NET</title><content type='html'>&lt;p&gt;Service Discovery is a key pattern in microservice architectures, where services need to find each other dynamically. Unlike monolithic applications, where all components are contained within a single executable, microservices are distributed across multiple instances, often across different servers, virtual machines, or containers. Service discovery simplifies the way these services locate one another, allowing for load balancing, failover, and flexibility.&lt;/p&gt;

&lt;h2&gt;What is Service Discovery?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Service Discovery&lt;/b&gt; refers to the process by which services in a distributed system dynamically find each other. Instead of hard-coding the addresses of service instances (which can change in a dynamic environment like Kubernetes), services register themselves with a centralized service registry. Other services query this registry to find the addresses of the services they need to communicate with.&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI69HjeFg324VXpbBQ7W57eK7tTq8ULc6A72F6Gkx8tMifP1uvOH215i5kPNQBg_HWGXCox0FAyD1YwIZoTw4Xq37Wg_-RRXIU_-6vvkwOjw_vboeI6Lx74CfQueTFbWVsXX115tUVZDYzToZOGUqck8sQ6Dg-zJbFjuA6-ZYaoIJ_1eWSyZqHflnmiYw/s1600/Screenshot%202024-10-27%20185428.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;service discovery microservice pattern&quot; border=&quot;0&quot; data-original-height=&quot;457&quot; data-original-width=&quot;952&quot; width=&quot;575&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI69HjeFg324VXpbBQ7W57eK7tTq8ULc6A72F6Gkx8tMifP1uvOH215i5kPNQBg_HWGXCox0FAyD1YwIZoTw4Xq37Wg_-RRXIU_-6vvkwOjw_vboeI6Lx74CfQueTFbWVsXX115tUVZDYzToZOGUqck8sQ6Dg-zJbFjuA6-ZYaoIJ_1eWSyZqHflnmiYw/s1600/Screenshot%202024-10-27%20185428.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h3&gt;Benefits:&lt;/h3&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Scalability&lt;/strong&gt;: New instances of services can be added dynamically.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Load Balancing&lt;/strong&gt;: Requests can be routed to different instances of the same service.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Fault Tolerance&lt;/strong&gt;: Dead services can be automatically removed from the registry.&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Types of Service Discovery:&lt;/h2&gt;
&lt;h3&gt;Client-Side Discovery&lt;/h3&gt;
&lt;p&gt;In client-side service discovery, the client directly queries the service registry to discover service instances and choose one to send a request to. This method requires the client to implement the logic for discovery and load balancing.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h3&gt;Server-Side Discovery&lt;/h3&gt;
&lt;p&gt;In server-side discovery, the client makes a request to a load balancer, and the load balancer queries the service registry to find available instances. The load balancer then forwards the request to an appropriate service instance.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Service Discovery in .NET/C#&lt;/h2&gt;
&lt;p&gt;In the .NET ecosystem, there are several tools and libraries that help with service discovery. These include:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Consul&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;etcd&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;ZooKeeper&lt;/strong&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Eureka (Spring Cloud for .NET)&lt;/strong&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;We&#39;ll focus on &lt;strong&gt;Consul&lt;/strong&gt;, which is one of the most popular choices for service discovery and distributed configuration.&lt;/p&gt;
&lt;h2&gt;Example Using Consul&lt;/h2&gt;
&lt;strong&gt;Step 1: Install Consul&lt;/strong&gt;
&lt;p&gt;Before diving into C#, we need to install and run a Consul agent. You can download Consul from &lt;a href=&quot;https://developer.hashicorp.com/consul/install&quot; target=&quot;_blank&quot;&gt;Consul Download&lt;/a&gt; and follow the &lt;a href=&quot;https://developer.hashicorp.com/consul/docs/install&quot; target=&quot;_blank&quot;&gt;installation&lt;/a&gt; instructions for your operating system.&lt;/p&gt;
&lt;p&gt;Once Consul is installed, you can start the agent by running:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
consul agent -dev
&lt;/pre&gt;
&lt;p&gt;This command starts a local Consul agent in development mode.Open url http://localhost:8500/ in browser , you will see below ui-&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbLu9nEbLHAjuJNIZpzZ4fvS502mnU_0UdvyoK5ME27BCiDDq7sZJv8G97lnpGW3oqaOH22MEnJM9DarZJq2xLzqlMkjF-m3NcBJKMZws2I41Swxi1SRiEZ3Hl1LY0dhQPagXtSaSd5g-_9EgBuv8zFmK1bGlHc00wj1cGVqtL5z0oVV-cpi5WRK6sStY/s1802/Screenshot%202024-10-27%20175349.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;consul ui&quot; border=&quot;0&quot; width=&quot;575&quot; data-original-height=&quot;575&quot; data-original-width=&quot;1802&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbLu9nEbLHAjuJNIZpzZ4fvS502mnU_0UdvyoK5ME27BCiDDq7sZJv8G97lnpGW3oqaOH22MEnJM9DarZJq2xLzqlMkjF-m3NcBJKMZws2I41Swxi1SRiEZ3Hl1LY0dhQPagXtSaSd5g-_9EgBuv8zFmK1bGlHc00wj1cGVqtL5z0oVV-cpi5WRK6sStY/s320/Screenshot%202024-10-27%20175349.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;clear: both;&quot;&gt;&lt;strong&gt;Step 2: Setting Up the API:&lt;/strong&gt;
&lt;p&gt;Now, let’s create a .NET Core API project &lt;b&gt;Service.Discovery.Demo.Api&lt;/b&gt;.This API will act as a service that needs to be discovered by other applications.&lt;/p&gt;
&lt;p&gt;Next, configure the API to register with the Consul upon startup. Add the Consul client package to the project&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
dotnet add package Consul
&lt;/pre&gt;
  &lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;strong&gt;Step 3: Register a Service in Consul&lt;/strong&gt;
&lt;p&gt;In the &lt;b&gt;Program.cs&lt;/b&gt;, we&#39;ll register a service with Consul. When a service starts, it registers itself with Consul using a unique service ID and some metadata.&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Consul Configuration
builder.Services.AddSingleton&amp;lt;IConsulClient&amp;gt;(p =&gt; new ConsulClient(consulConfig =&gt;
{
    var consulHost = builder.Configuration[&quot;Consul:Host&quot;];
    var consulPort = Convert.ToInt32(builder.Configuration[&quot;Consul:Port&quot;]);
    consulConfig.Address = new Uri($&quot;http://{consulHost}:{consulPort}&quot;);
}));
builder.Services.AddSingleton&amp;lt;IServiceDiscovery, ServiceDiscovery&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;Create a class named &lt;b&gt;ServiceDiscovery&lt;/b&gt; that implements the &lt;b&gt;IServiceDiscovery&lt;/b&gt; interface to handle service registration:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
//IServiceDiscovery interface
public interface IServiceDiscovery
{
    Task RegisterServiceAsync(string serviceName, string serviceId, string serviceAddress, int servicePort);
    Task RegisterServiceAsync(AgentServiceRegistration serviceRegistration);

    Task DeRegisterServiceAsync(string serviceId);
}
//IServiceDiscovery Implementation
 public class ServiceDiscovery : IServiceDiscovery
 {
     private readonly IConsulClient _consulClient;

     public ServiceDiscovery(IConsulClient consulClient)
     {
         _consulClient = consulClient;
     }        

     public async Task RegisterServiceAsync(string serviceName, string serviceId, string serviceAddress, int servicePort)
     {
         var registration = new AgentServiceRegistration
         {
             ID = serviceId,
             Name = serviceName,
             Address = serviceAddress,
             Port = servicePort
         };
         await _consulClient.Agent.ServiceDeregister(serviceId);
         await _consulClient.Agent.ServiceRegister(registration);
     }

     public async Task RegisterServiceAsync(AgentServiceRegistration serviceRegistration)
     {
         await _consulClient.Agent.ServiceDeregister(serviceRegistration.ID);
         await _consulClient.Agent.ServiceRegister(serviceRegistration);
     }
     public async Task DeRegisterServiceAsync(string serviceId)
     {
         await _consulClient.Agent.ServiceDeregister(serviceId);
     }
 }
&lt;/pre&gt;
&lt;p&gt;Now add the service registration logic in &lt;b&gt;Program.cs&lt;/b&gt; file&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
app.MapControllers();
#region Service Registration
var discovery = app.Services.GetRequiredService&amp;lt;IServiceDiscovery&amp;gt;();
var lifetime = app.Services.GetRequiredService&amp;lt;IHostApplicationLifetime&amp;gt;();
var serviceName = builder.Configuration[&quot;ServiceRegistration:serviceName&quot;];
var serviceId = builder.Configuration[&quot;ServiceRegistration:serviceId&quot;];
var serviceAddress = builder.Configuration[&quot;ServiceRegistration:servcieHost&quot;];
var servicePort = Convert.ToInt32(builder.Configuration[&quot;ServiceRegistration:servciePort&quot;]);

lifetime.ApplicationStarted.Register(async () =&gt;
{
    var registration = new AgentServiceRegistration
    {
        ID = serviceId,
        Name = serviceName,
        Address = serviceAddress,
        Port = servicePort
    };
    await discovery.RegisterServiceAsync(registration);
});

lifetime.ApplicationStopping.Register(async () =&gt;
{
    await discovery.DeRegisterServiceAsync(serviceId);
});
#endregion
&lt;/pre&gt;
&lt;p&gt;In the above code we are getting host, post and other configuration values from &lt;b&gt;appsettings.json&lt;/b&gt; file. Add the below configuration in &lt;b&gt;appsettings.json&lt;/b&gt; file.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
{
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  /* Consul Config*/
  &quot;Consul&quot;: {
    &quot;Host&quot;: &quot;localhost&quot;,
    &quot;Port&quot;: 8500
  },
  /* Service Registration Config*/
  &quot;ServiceRegistration&quot;: {
    &quot;serviceName&quot;: &quot;DemoApi&quot;,
    &quot;serviceId&quot;: &quot;6a5f4761-ac01-4407-a81b-831a28894f0f&quot;,
    &quot;servcieHost&quot;: &quot;locahost&quot;,
    &quot;servciePort&quot;: &quot;7087&quot;
  }
}
&lt;/pre&gt;
&lt;p&gt;With these configurations, the API will register itself with the Consul upon startup and deregister upon shutdown.&lt;/p&gt;
  &lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;strong&gt;Step 4: Creating the Client Application&lt;/strong&gt;
&lt;p&gt;Next, create a console application named &lt;b&gt;Service.Discovery.Demo.Client&lt;/b&gt; and add the Consul client package to the project.&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
dotnet add package Consul
&lt;/pre&gt;
&lt;p&gt;In the &lt;b&gt;Program.cs&lt;/b&gt; file, configure the Consul client to discover services:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using Consul;

using (var client = new ConsulClient(consulConfig =&gt;
{
    consulConfig.Address = new Uri(&quot;http://localhost:8500&quot;);
}))
{
    var services = await client.Catalog.Service(&quot;DemoAPi&quot;);
    foreach (var service in services.Response)
    {
        Console.WriteLine($&quot;Service ID: {service.ServiceID}, Address: {service.ServiceAddress}, Port: {service.ServicePort}&quot;);
    }
}
Console.ReadLine();
&lt;/pre&gt;
&lt;p&gt;This code snippet retrieves all instances of the Api service registered with the Consul.&lt;/p&gt;
&lt;strong&gt;Step 5: Testing the API and Client Application:&lt;/strong&gt;
&lt;p&gt;Below is the project structure&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFkvFFyNXodLLR3ue_NaZ8Yu3pvUpS986wZsh7p7nQ5uXCZ7ENtrsfehQDxCfmPxXb6ErVgbYvvKZvoA52vt8h5Xf455fS0Sn3ozdPFZO7USEZqlKSPJJAgItFYR9bjhThJTk3C9xhj0YVnG0icRRa1pak-W4_XdTFRgR61XUd1i2OuBQuEMbVFlsLKIM/s1893/Screenshot%202024-10-27%20182232.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;project structure&quot; border=&quot;0&quot; width=&quot;575&quot; data-original-height=&quot;852&quot; data-original-width=&quot;1893&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFkvFFyNXodLLR3ue_NaZ8Yu3pvUpS986wZsh7p7nQ5uXCZ7ENtrsfehQDxCfmPxXb6ErVgbYvvKZvoA52vt8h5Xf455fS0Sn3ozdPFZO7USEZqlKSPJJAgItFYR9bjhThJTk3C9xhj0YVnG0icRRa1pak-W4_XdTFRgR61XUd1i2OuBQuEMbVFlsLKIM/s400/Screenshot%202024-10-27%20182232.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p style=&quot;clear: both;&quot;&gt;Now run both applications using the command dotnet run. When this application starts, the Consul portal will display the registered service.&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_gqaT25-Nt-_9Q7z4IhxJ5FY4ip8xi4pm0O8KmRLlezxHfUYwX3baScy840ZiI1M33ad-F941hYcgTEeHNaNijdCR3jGAIMtvjqFNG0hiWDoUnJ4-02KyLnJslaiXEe_pzkgxTO8NB1KfcQZ1E4U7rxuN05fGFv3NU04U0QEKPN3tdxF5UZbRSduIV98/s1861/Screenshot%202024-10-27%20182524.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;consul registered services&quot; border=&quot;0&quot; width=&quot;575&quot; data-original-height=&quot;832&quot; data-original-width=&quot;1861&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_gqaT25-Nt-_9Q7z4IhxJ5FY4ip8xi4pm0O8KmRLlezxHfUYwX3baScy840ZiI1M33ad-F941hYcgTEeHNaNijdCR3jGAIMtvjqFNG0hiWDoUnJ4-02KyLnJslaiXEe_pzkgxTO8NB1KfcQZ1E4U7rxuN05fGFv3NU04U0QEKPN3tdxF5UZbRSduIV98/s400/Screenshot%202024-10-27%20182524.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p style=&quot;clear: both;&quot;&gt;Below is the output of the console application&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7ZKQaXmbczgC7HDXKv0egSSIT12l7yBCPNt0nRhvlgVYindsl3SoRvv64kygtGqD1j-Z9jkX29O966OzI4C96f0b_Hz7_YJWI3390kjtuyn2EPftp5FF-_Dr4lLYCO21SKGJg4qu_4JXiVNMSqtysogdGQZw4KDLI_F_5csY3wMws38xgO8oJEWyp-GU/s1010/Screenshot%202024-10-27%20182845.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;service discovery output&quot; border=&quot;0&quot; width=&quot;575&quot; data-original-height=&quot;118&quot; data-original-width=&quot;1010&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7ZKQaXmbczgC7HDXKv0egSSIT12l7yBCPNt0nRhvlgVYindsl3SoRvv64kygtGqD1j-Z9jkX29O966OzI4C96f0b_Hz7_YJWI3390kjtuyn2EPftp5FF-_Dr4lLYCO21SKGJg4qu_4JXiVNMSqtysogdGQZw4KDLI_F_5csY3wMws38xgO8oJEWyp-GU/s400/Screenshot%202024-10-27%20182845.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Service discovery is a crucial component in building microservices at scale. In this post, we covered the basics of service discovery, types of service discovery (client-side and server-side), and demonstrated how to use Consul in a .NET application for registering and discovering services.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/MicroServicesDesignPatterns/tree/main/ServcieDiscovery&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;service discovery example in .net&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/968758156126943904/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/10/service-discovery-in-microservices-net-with-consul.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/968758156126943904'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/968758156126943904'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/10/service-discovery-in-microservices-net-with-consul.html' title='Service Discovery in Microservices with C# and .NET'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI69HjeFg324VXpbBQ7W57eK7tTq8ULc6A72F6Gkx8tMifP1uvOH215i5kPNQBg_HWGXCox0FAyD1YwIZoTw4Xq37Wg_-RRXIU_-6vvkwOjw_vboeI6Lx74CfQueTFbWVsXX115tUVZDYzToZOGUqck8sQ6Dg-zJbFjuA6-ZYaoIJ_1eWSyZqHflnmiYw/s72-c/Screenshot%202024-10-27%20185428.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-5051915766284435509</id><published>2024-10-12T17:30:00.111+05:30</published><updated>2024-11-11T02:05:22.942+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="API Gateway"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservice Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><category scheme="http://www.blogger.com/atom/ns#" term="Ocelot Api Gateway"/><title type='text'>Implementing an API gateway in a .NET Core application</title><content type='html'>&lt;p&gt;The &lt;b&gt;API Gateway Pattern&lt;/b&gt; is a design pattern used in &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/09/introduction-to-microservices.html&quot; target=&quot;_blank&quot;&gt;microservices architecture&lt;/a&gt;. It acts as a single entry point for clients, managing all interactions between them and the backend services. This pattern simplifies client interactions by encapsulating the complexities of multiple microservices, providing features like request routing, load balancing, caching, and security.&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtD0raAgmvU3I5QCDAuEcvtYbzcVk1nmNmyv7-QdXfACHoXFqLFnNRDovhWia5xs9MGVixcFeRITfYEcW4UILS13Va4X6LQeGOqpgM5C-qYhPhyphenhyphenIfJrgJSvasECkH0IXWvlk7v6D1NmrfU_YzN5hfVijSPAnZ1UHyu7qBWVgF2fGaPWCnQD4ibtj4G1ho/s1600/Screenshot%202024-10-20%20111555.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; &quot;&gt;&lt;img alt=&quot;api gateway&quot; border=&quot;0&quot; data-original-height=&quot;400&quot; data-original-width=&quot;885&quot; width=&quot;500&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtD0raAgmvU3I5QCDAuEcvtYbzcVk1nmNmyv7-QdXfACHoXFqLFnNRDovhWia5xs9MGVixcFeRITfYEcW4UILS13Va4X6LQeGOqpgM5C-qYhPhyphenhyphenIfJrgJSvasECkH0IXWvlk7v6D1NmrfU_YzN5hfVijSPAnZ1UHyu7qBWVgF2fGaPWCnQD4ibtj4G1ho/s1600/Screenshot%202024-10-20%20111555.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Why Use an API Gateway?&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Centralized Entry Point&lt;/strong&gt;: Clients interact with one endpoint rather than multiple services.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Decoupling of Client and Services&lt;/strong&gt;: The gateway handles communication with services, hiding service details from clients.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Cross-cutting Concerns&lt;/strong&gt;: It manages functionalities like authentication, logging, rate-limiting, etc., across services.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Load Balancing&lt;/strong&gt;: Distributes incoming traffic efficiently to backend services.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Security&lt;/strong&gt;: Acts as a gatekeeper, providing security features like SSL termination and token validation.&lt;/li&gt;&lt;/ol&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Introduction to Ocelot&lt;/h2&gt;
&lt;p&gt;Ocelot is an open-source API Gateway, designed for microservice architecture. This is based on .NET Core. Ocelot is a set of middleware designed for features such as routing, caching, security, rate limiting, etc. please refer to the &lt;a href=&quot;https://ocelot.readthedocs.io/en/latest/introduction/bigpicture.html&quot; target=&quot;_blank&quot;&gt;link&lt;/a&gt; for more details.&lt;/p&gt;
&lt;h2&gt;Create Simple Services&lt;/h2&gt;
&lt;p&gt;Let&#39;s build a simple &lt;b&gt;API Gateway&lt;/b&gt; using &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/net-core.html&quot; target=&quot;_blank&quot;&gt;ASP.NET Core&lt;/a&gt;.We will be creating two simple services for demo purposes.Let us start two services – one is Product Service and another one is Customer Service&lt;/p&gt;
&lt;strong&gt; Setting up APIs&lt;/strong&gt;
&lt;p&gt;Product Service will looks like below-&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using Microsoft.AspNetCore.Mvc;
using models = Product.MicroService.Models;

namespace Product.MicroService.Controllers
{
    [ApiController]
    [Route(&quot;api/[controller]&quot;)]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            var products = new List&amp;lt;models.Product&amp;gt;
            {
                new models.Product { Id = 1, ProductName = &quot;Iphone&quot;, Rate = 2000 },
                new models.Product { Id = 2, ProductName = &quot;Samsung Galaxy&quot;, Rate = 1800 }
            };
            return Ok(products);
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;p&gt;Customer Service will looks like below-&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;using Microsoft.AspNetCore.Mvc;
using models = Customer.MicroService.Models;

namespace Customer.MicroService.Controllers
{
    [ApiController]
    [Route(&quot;api/[controller]&quot;)]
    public class CustomerController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetAll()
        {
            var customers = new List&amp;lt;models.Customer&amp;gt;
            {
                new models.Customer {Id = 1, Name = &quot;Manish&quot;, Email = &quot;test@gmail.com&quot;},
                new models.Customer{Id = 2, Name = &quot;Ashis&quot;, Email = &quot;xyz@gmail.com&quot; }
            };
            return Ok(customers);
        }
    }
}

&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;strong&gt;Implement Gateway using Ocelot&lt;/strong&gt;
&lt;p&gt;Let us go ahead and create an empty ASP.NET Core project. And then install the Ocelot package.&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
Install-Package Ocelot
&lt;/pre&gt;
&lt;strong&gt;Configure Ocelot&lt;/strong&gt;
&lt;p&gt;We need to create a JSON file – ocelot.json at the root project level in Gateway project.Let us modify the file and configure the Ocelot.json file&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
{
  &quot;GlobalConfiguration&quot;: {
    &quot;BaseUrl&quot;: &quot;http://localhost:5003&quot;
  },
  &quot;Routes&quot;: [
    {
      &quot;UpstreamPathTemplate&quot;: &quot;/gateway/product&quot;,
      &quot;UpstreamHttpMethod&quot;: [ &quot;Get&quot; ],
      &quot;DownstreamPathTemplate&quot;: &quot;/api/product&quot;,
      &quot;DownstreamScheme&quot;: &quot;http&quot;,
      &quot;DownstreamHostAndPorts&quot;: [
        {
          &quot;Host&quot;: &quot;localhost&quot;,
          &quot;Port&quot;: 5160
        }
      ]
    },
    {
      &quot;UpstreamPathTemplate&quot;: &quot;/gateway/customer&quot;,
      &quot;UpstreamHttpMethod&quot;: [ &quot;Get&quot; ],
      &quot;DownstreamPathTemplate&quot;: &quot;/api/customer&quot;,
      &quot;DownstreamScheme&quot;: &quot;http&quot;,
      &quot;DownstreamHostAndPorts&quot;: [
        {
          &quot;Host&quot;: &quot;localhost&quot;,
          &quot;Port&quot;: 5173
        }
      ]
    }
  ]
}
&lt;/pre&gt;
&lt;p&gt;This configuration maps incoming requests to specific downstream services:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;/gateway/product&lt;/strong&gt; will forward requests to the &lt;strong&gt;Product&lt;/strong&gt; service running on &lt;strong&gt;localhost:5160&lt;/strong&gt;.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;/gateway/customer&lt;/strong&gt; will forward requests to the &lt;strong&gt;Customer&lt;/strong&gt; service running on &lt;strong&gt;localhost:5173&lt;/strong&gt;.&lt;/li&gt;&lt;/ul&gt;
&lt;strong&gt;Configure the Ocelot Middleware&lt;/strong&gt;
&lt;p&gt;Now we need to configure our project to use the &lt;b&gt;ocelot.json&lt;/b&gt; fine. These configuration needs to be done in &lt;b&gt;Program.cs&lt;/b&gt; file as below,&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
builder.Configuration.AddJsonFile(&quot;ocelot.json&quot;, optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);
&lt;/pre&gt;
&lt;p&gt;The namespaces which need to be imported are,&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
&lt;/pre&gt;
&lt;p&gt;Now add the Ocelot Middleware in &lt;b&gt;Program.cs&lt;/b&gt;&lt;/p&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
await app.UseOcelot();
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;p&gt;As a final step, to run all the services simultaneously, right click on Solution and select Properties, update the below highlighted settings.&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtsbb9J50CZRWsUDN7fVyu8QBf9HL_YaY3Dhg3D-ZfzAXCrx4rP69-h5zXDTzwp-4KpLiW16_KjBHOW4IrPzqEuOVlqsNRu2wHldnypTJ9ykUcgUKEeXaqvdCx0gCtUKt6CN7_1GPcBRrHS04pC2T9_eKXk2_AwAHShUYV7fa6dUGHZSgSu1xG7Xj9314/s1171/Screenshot%202024-10-20%20104626.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; width=&quot;500&quot; data-original-height=&quot;814&quot; data-original-width=&quot;1171&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtsbb9J50CZRWsUDN7fVyu8QBf9HL_YaY3Dhg3D-ZfzAXCrx4rP69-h5zXDTzwp-4KpLiW16_KjBHOW4IrPzqEuOVlqsNRu2wHldnypTJ9ykUcgUKEeXaqvdCx0gCtUKt6CN7_1GPcBRrHS04pC2T9_eKXk2_AwAHShUYV7fa6dUGHZSgSu1xG7Xj9314/s320/Screenshot%202024-10-20%20104626.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p style=&quot;clear: both;&quot;&gt;Now instead of executing the downstream service, let us go ahead and execute the gateway and see the result.Execute the below Gateway end points and see whether we are getting the expected result&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;/gateway/product&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi00ODBonnhKL2Git3wH5uF1MTASDRUmtZAMPSMVP76VofQ6uUwGasoy23o_TPw87MUEmUW_YEzFiNhidwiYwRT2ejSjwNPnn-ig-aFarh7m3QumJSta5TGHiuc6o25dDGYPkNmdBpY0XMFygJJe5_FnllB1kZfTRx6NjomYIfxyuSVzu_ghXSTRPhWFfI/s1330/Screenshot%202024-10-20%20104946.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; width=&quot;500&quot; data-original-height=&quot;547&quot; data-original-width=&quot;1330&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi00ODBonnhKL2Git3wH5uF1MTASDRUmtZAMPSMVP76VofQ6uUwGasoy23o_TPw87MUEmUW_YEzFiNhidwiYwRT2ejSjwNPnn-ig-aFarh7m3QumJSta5TGHiuc6o25dDGYPkNmdBpY0XMFygJJe5_FnllB1kZfTRx6NjomYIfxyuSVzu_ghXSTRPhWFfI/s320/Screenshot%202024-10-20%20104946.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p style=&quot;clear: both;&quot;&gt;&lt;strong&gt;/gateway/customer&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLm-iZiNWHMFYm-6_OotmUR8OG_uqSCcPHjMGvv4MYjic9I7G-FCc0SBKmAqHPyoQ_KyYXOr6YGzHvp-4_zGrnRfOcGILR9lNaBwPHCfRAKvW4vLpKZwPm_k_CreHRW9iKnUsHMjmUREnmEfejiDyEtErrJrSclCCUjV0Cw8lisYgltU3fNo_gGb01lXQ/s1323/Screenshot%202024-10-20%20105240.png&quot; style=&quot;display: block; padding: 1em 0; text-align: left; &quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; width=&quot;500&quot; data-original-height=&quot;562&quot; data-original-width=&quot;1323&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLm-iZiNWHMFYm-6_OotmUR8OG_uqSCcPHjMGvv4MYjic9I7G-FCc0SBKmAqHPyoQ_KyYXOr6YGzHvp-4_zGrnRfOcGILR9lNaBwPHCfRAKvW4vLpKZwPm_k_CreHRW9iKnUsHMjmUREnmEfejiDyEtErrJrSclCCUjV0Cw8lisYgltU3fNo_gGb01lXQ/s320/Screenshot%202024-10-20%20105240.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;API Gateway Pattern&lt;/b&gt; helps manage complex microservice architectures by providing a unified interface for clients, simplifying the communication between clients and services. Using tools like Ocelot in .NET makes it straightforward to implement an API Gateway that handles routing, security, and load balancing efficiently.&lt;/p&gt;
&lt;p&gt;This example is a basic introduction. In a production environment, you would also implement additional features like authentication, rate-limiting, logging, and more.&lt;/p&gt;
&lt;p&gt;The full source code is available here:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/MicroServicesDesignPatterns/tree/main/APIGateway&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/5051915766284435509/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/10/microservice-design-pattern-api-gateway.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5051915766284435509'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/5051915766284435509'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/10/microservice-design-pattern-api-gateway.html' title='Implementing an API gateway in a .NET Core application'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtD0raAgmvU3I5QCDAuEcvtYbzcVk1nmNmyv7-QdXfACHoXFqLFnNRDovhWia5xs9MGVixcFeRITfYEcW4UILS13Va4X6LQeGOqpgM5C-qYhPhyphenhyphenIfJrgJSvasECkH0IXWvlk7v6D1NmrfU_YzN5hfVijSPAnZ1UHyu7qBWVgF2fGaPWCnQD4ibtj4G1ho/s72-c/Screenshot%202024-10-20%20111555.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-808243643018749299</id><published>2024-09-17T17:30:00.011+05:30</published><updated>2024-10-28T07:36:50.116+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Microservice Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><title type='text'>Microservice Design Patterns</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s379/Screenshot%202024-09-14%20222237.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Microservice Design Patterns&quot; border=&quot;0&quot; width=&quot;138&quot; height=&quot;138&quot; data-original-height=&quot;377&quot; data-original-width=&quot;379&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s320/Screenshot%202024-09-14%20222237.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p&gt;Microservices architecture is a powerful approach to building complex, scalable applications by breaking them down into smaller, independent services. However, designing and managing microservices effectively can be challenging. This is where microservice design patterns come into play. These patterns provide proven solutions to common challenges in microservice architecture, helping developers create systems that are scalable, resilient, and maintainable.&lt;/p&gt;
&lt;h3 style=&quot;clear: both;&quot;&gt;1. &lt;strong&gt;&lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/10/microservice-design-pattern-api-gateway.html&quot;&gt;API Gateway Pattern&lt;/a&gt;&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: In a microservice architecture, clients need to interact with multiple services, leading to increased complexity and potential performance bottlenecks.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Implement an API Gateway that acts as a single entry point for all client requests. The gateway routes requests to the appropriate microservices and can handle tasks like authentication, rate limiting, and load balancing.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Netflix uses Zuul as an API Gateway to handle all incoming traffic and route it to the appropriate services.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h3&gt;2. &lt;strong&gt;Circuit Breaker Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Microservices often depend on other services. If one service fails, it can cause a cascading failure across the entire system.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: The Circuit Breaker pattern prevents this by wrapping calls to external services. If a service is down or slow, the circuit breaker trips, returning a fallback response instead of repeatedly trying to contact the failing service.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Hystrix, a popular library from Netflix, implements the Circuit Breaker pattern to improve system resilience.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;3. &lt;strong&gt;&lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/10/service-discovery-in-microservices-net-with-consul.html&quot; target=&quot;_blank&quot;&gt;Service Discovery Pattern&lt;/a&gt;&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: In dynamic environments where services are constantly being deployed or scaled, finding the location of a service can be challenging.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Use Service Discovery to maintain a registry of available services and their instances. Services can register themselves and query the registry to locate other services.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Consul and Eureka are commonly used service discovery tools that allow microservices to discover and communicate with each other efficiently.&lt;/p&gt;
&lt;h3&gt;4. &lt;strong&gt;Saga Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Managing transactions across multiple microservices can be complex since traditional ACID transactions are difficult to implement.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: The Saga pattern breaks down a transaction into smaller steps, each handled by a different service. If one step fails, the saga pattern ensures that compensating actions are taken to rollback the previous steps, ensuring consistency.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: An order processing system where creating an order, charging a customer, and updating inventory are handled by separate services. If inventory update fails, the Saga pattern triggers a rollback on the payment service.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;5. &lt;strong&gt;Event Sourcing Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Keeping track of the state of a system, especially when multiple services modify the same data, can be difficult.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Event Sourcing captures changes to the application state as a sequence of events. Each event represents a state change, and the current state of an entity can be derived by replaying these events.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Systems like CQRS (Command Query Responsibility Segregation) often use Event Sourcing to ensure that the read and write sides of an application are eventually consistent.&lt;/p&gt;
&lt;h3&gt;6. &lt;strong&gt;Strangler Fig Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Migrating a monolithic application to a microservices architecture can be risky and complex if done all at once.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: The Strangler Fig pattern allows for incremental migration by slowly replacing parts of the monolith with microservices. Over time, the monolith &quot;strangles&quot; as more of its functionality is replaced.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Start by extracting a single feature into a microservice and route relevant requests to it. Gradually, move other features to microservices until the monolith is fully deprecated.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;7. &lt;strong&gt;Bulkhead Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: A failure in one part of a system should not bring down the entire application.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: The Bulkhead pattern isolates different parts of the system, so that a failure in one part doesn’t affect others. This can be achieved by partitioning services or resources, such as thread pools or connection pools.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: If one microservice is facing high traffic, the Bulkhead pattern ensures that it doesn’t exhaust all system resources, allowing other services to continue functioning normally.&lt;/p&gt;
&lt;h3&gt;8. &lt;strong&gt;Database per Service Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Sharing a single database across multiple microservices can lead to tight coupling and difficulties in scaling.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Each microservice should have its own database, allowing services to be more autonomous, scalable, and resilient. This pattern aligns with the principle of decentralized data management in microservices.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: An e-commerce application where the order service, inventory service, and payment service each have their own databases, enabling independent scaling and deployment.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h3&gt;9. &lt;strong&gt;Sidecar Pattern&lt;/strong&gt;&lt;/h3&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Some functionalities, such as logging, monitoring, or communication, need to be shared across multiple microservices, leading to code duplication.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: The Sidecar pattern involves deploying helper components alongside microservices in the same container or pod. These sidecars handle cross-cutting concerns without bloating the main service code.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Service mesh solutions like Istio use the Sidecar pattern to handle network-related concerns, such as traffic management and security, without modifying the microservices themselves.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Microservice design patterns are essential tools for building resilient, scalable, and maintainable systems. By applying these patterns thoughtfully, you can overcome many of the challenges inherent in microservice architectures, ensuring that your system is robust and adaptable to change.&lt;/p&gt;
&lt;p&gt;Whether you are starting with microservices or optimizing an existing architecture, understanding these design patterns will significantly enhance your ability to design effective solutions.&lt;/p&gt;
&lt;p&gt;Happy Learning!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/808243643018749299/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/microservice-design-patterns.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/808243643018749299'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/808243643018749299'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/microservice-design-patterns.html' title='Microservice Design Patterns'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s72-c/Screenshot%202024-09-14%20222237.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-1628887648068110420</id><published>2024-09-16T17:30:00.031+05:30</published><updated>2024-11-11T02:05:52.663+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservice Architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="Microservices"/><title type='text'>What are Microservices?</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s379/Screenshot%202024-09-14%20222237.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Microservcies&quot; border=&quot;0&quot; width=&quot;138&quot; height=&quot;138&quot; data-original-height=&quot;377&quot; data-original-width=&quot;379&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s320/Screenshot%202024-09-14%20222237.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;In today’s fast-paced tech world, businesses need to be agile and responsive to change. One way to achieve this is through the use of microservices. But what exactly are microservices, and why are they so popular?&lt;/p&gt;

&lt;h2&gt;What Are Microservices?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Microservices&lt;/b&gt; is an architectural style in software development where an application is composed of small, independent services, each responsible for a specific function. These services communicate with each other, often via APIs, and work together to fulfill the overall requirements of the application.&lt;/p&gt;
&lt;p&gt;Unlike the traditional monolithic architecture, where all components of an application are interconnected and run as a single unit, microservices allow each service to be developed, deployed, and scaled independently. This modular approach gives greater flexibility in managing complex applications.&lt;/p&gt;

&lt;h2&gt;Key Features of Microservices&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: Microservices function as independent units, meaning developers can work on different parts of an application simultaneously without causing interference.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Decentralization&lt;/strong&gt;: Unlike monolithic architectures where a central database manages the entire application, microservices often use decentralized data management. Each service may manage its own database, leading to better autonomy.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Scalability&lt;/strong&gt;: Since microservices are independently deployable, individual services can be scaled based on demand without scaling the entire system, making resource management more efficient.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Technology Diversity&lt;/strong&gt;: Teams can use different programming languages, frameworks, or technologies for each service, allowing them to choose the best tools for the job.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Fault Isolation&lt;/strong&gt;: In a monolithic application, a failure in one part can potentially bring down the entire system. With microservices, a failure in one service doesn&#39;t necessarily impact others, leading to increased system resilience.&lt;/li&gt;&lt;/ol&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example of Microservices in Action&lt;/h2&gt;
&lt;p&gt;Imagine an e-commerce website. In a microservices architecture, there might be separate services for:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;User authentication&lt;/strong&gt;: Handles login and user management.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Product catalog&lt;/strong&gt;: Manages the listing and description of products.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Shopping cart&lt;/strong&gt;: Tracks items a user has selected for purchase.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Order processing&lt;/strong&gt;: Manages orders and payments.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Each of these services can be developed and deployed independently, making the overall system more flexible and easier to maintain.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Advantages of Microservices&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Faster Time to Market&lt;/strong&gt;: Teams can develop, test, and deploy services independently, leading to shorter development cycles and quicker releases.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Continuous Delivery&lt;/strong&gt;: Microservices enable continuous integration and delivery practices, allowing frequent updates without impacting the entire system.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Flexibility in Development&lt;/strong&gt;: Teams can adopt different technologies for different services, enhancing flexibility in the development process.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Improved Fault Tolerance&lt;/strong&gt;: A failure in one service won&#39;t necessarily disrupt the entire application, leading to better fault tolerance.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Challenges of Microservices&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Complexity in Management&lt;/strong&gt;: Managing multiple services introduces complexity, requiring sophisticated monitoring, logging, and security practices.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Data Consistency&lt;/strong&gt;: Since each service may have its own database, ensuring data consistency across services can be challenging.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Inter-service Communication&lt;/strong&gt;: Efficient communication between microservices is essential and can become complex when scaling.&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Microservices architecture provides a flexible, scalable approach to building complex applications by breaking them into smaller, independent services. While it introduces new challenges, the benefits in terms of agility, resilience, and scalability make it an attractive choice for modern software development.&lt;/p&gt;
&lt;p&gt;Happy Learning!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/1628887648068110420/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/introduction-to-microservices.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1628887648068110420'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1628887648068110420'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/introduction-to-microservices.html' title='What are Microservices?'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoFYoyJ73VHPpqqqrrHymJ49qchyphenhyphen56PkcdaDT1236t_aAoi-OoZKgG1wKa0rb_tKoap2iXrgv1E1XeTS2oTlXacvxj_8DQkGjn_8dZmb2rcK5X6r44Ub0U_5mzWiIIOjHzAoYaunbzF56_RjQiZTHOn3l44g-DwgAdOU80A7lYM8bAYUwmXRfiE2ZhMhA/s72-c/Screenshot%202024-09-14%20222237.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-1785823957360286883</id><published>2024-09-13T17:30:00.004+05:30</published><updated>2024-11-11T02:06:03.700+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Behavioral Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Memento Design Pattern"/><title type='text'>Memento Design Pattern in C#</title><content type='html'>&lt;p&gt;The &lt;b&gt;Memento Design Pattern&lt;/b&gt; is a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/design-pattern.html&quot; target=&quot;_blank&quot;&gt;Behavioral Design Pattern&lt;/a&gt; that can restore an object to its previous state. This pattern is useful for scenarios where you need to perform an undo or rollback operation in your application. The Memento pattern captures an object’s internal state so that the object can be restored to this state later. It is especially useful when implementing undo functionality in an application.&lt;/p&gt;
&lt;h2&gt;Component of Memento Design Pattern&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;strong&gt;Originator&lt;/strong&gt;: The object whose state you want to save or restore.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Memento&lt;/strong&gt;: Stores the internal state of the &lt;b&gt;Originator&lt;/b&gt;. It has two interfaces:&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Caretaker Interface&lt;/strong&gt;: This interface provides no access to the internal state of the &lt;b&gt;Memento&lt;/b&gt;. It is used by the &lt;b&gt;Caretaker&lt;/b&gt; to manage the &lt;b&gt;Memento&lt;/b&gt; without modifying it.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Originator Interface&lt;/strong&gt;: This interface allows the &lt;b&gt;Originator&lt;/b&gt; to access the &lt;b&gt;Memento&lt;/b&gt; to restore its state.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Caretaker&lt;/strong&gt;: The object that requests the saving and restoring of the &lt;b&gt;Originator&lt;/b&gt;’s state.&lt;/li&gt;&lt;/ol&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Implementing Memento Pattern in C#&lt;/h2&gt;
&lt;b&gt;Define the Memento&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace MementoPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Memento class to hold the state
    /// &amp;lt;/summary&amp;gt;
    public class Memento
    {
        public string State { get; private set; }

        public Memento(string state)
        {
            State = state;
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Implement the Originator&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace MementoPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Originator class that uses Memento to save and restore state
    /// &amp;lt;/summary&amp;gt;
    public class Originator
    {
        public string State { get; set; }

        public void SetState(string state)
        {
            Console.WriteLine($&quot;Setting state to: {state}&quot;);
            State = state;
        }

        public Memento SaveStateToMemento()
        {
            Console.WriteLine(&quot;Saving state to Memento.&quot;);
            return new Memento(State);
        }

        public void RestoreStateFromMemento(Memento memento)
        {
            State = memento.State;
            Console.WriteLine($&quot;Restored state from Memento: {State}&quot;);
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Create the Caretaker&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace MementoPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Caretaker class that manages Mementos
    /// &amp;lt;/summary&amp;gt;
    public class Caretaker
    {
        private List&amp;lt;Memento&amp;gt; _mementoList = new List&amp;lt;Memento&amp;gt;();

        public void AddMemento(Memento memento)
        {
            _mementoList.Add(memento);
            Console.WriteLine(&quot;State saved to Caretaker.&quot;);
        }

        public Memento GetMemento(int index)
        {
            return _mementoList[index];
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Test the Memento Pattern(Program.cs)&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// Create Originator and Caretaker objects
using MementoPattern;

Originator originator = new Originator();
Caretaker caretaker = new Caretaker();

// Set and save some states
originator.SetState(&quot;State 1&quot;);
caretaker.AddMemento(originator.SaveStateToMemento());

originator.SetState(&quot;State 2&quot;);
caretaker.AddMemento(originator.SaveStateToMemento());

originator.SetState(&quot;State 3&quot;);
caretaker.AddMemento(originator.SaveStateToMemento());

// Restore previous states
Console.WriteLine(&quot;\nRestoring states:&quot;);
originator.RestoreStateFromMemento(caretaker.GetMemento(0));
originator.RestoreStateFromMemento(caretaker.GetMemento(1));
Console.ReadLine();
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Explanation&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;The &lt;b&gt;Originator&lt;/b&gt; class represents the object whose state needs to be saved and restored. It has a &lt;b&gt;SetState&lt;/b&gt; method for changing the state and a &lt;b&gt;SaveStateToMemento&lt;/b&gt; method for saving the current state to a &lt;b&gt;Memento&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The &lt;b&gt;Memento&lt;/b&gt; class stores the state of the &lt;b&gt;Originator&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The &lt;b&gt;Caretaker&lt;/b&gt; class is responsible for keeping a collection of &lt;b&gt;Memento&lt;/b&gt; objects. It doesn’t modify or access the internal state of the &lt;b&gt;Memento&lt;/b&gt;, but it can store and retrieve them.&lt;/li&gt;&lt;/ol&gt;
&lt;h2&gt;Output&lt;/h2&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgd7dvwQXLzRff9pQ56_-iRd9_CQkxq5Z1OmB5-kjFHk61kT4MaS1QpWjw7qo_Sc0qvRXqaAYu_dBsAh7tMBw-_cbokN1ZiXSMgUVIDtimhA3uTzOJGHorlUPrR3-fsPb7wRoPT1h9_Ui8HC9-B0UFPeA8mIcZxl43ZHuugRQXxqHadwsU3WYQwFwEjfMQ/s1600/Screenshot%202024-09-12%20204037.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;Memento Design Pattern in C#&quot; border=&quot;0&quot; data-original-height=&quot;396&quot; data-original-width=&quot;722&quot; width=&quot;700&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgd7dvwQXLzRff9pQ56_-iRd9_CQkxq5Z1OmB5-kjFHk61kT4MaS1QpWjw7qo_Sc0qvRXqaAYu_dBsAh7tMBw-_cbokN1ZiXSMgUVIDtimhA3uTzOJGHorlUPrR3-fsPb7wRoPT1h9_Ui8HC9-B0UFPeA8mIcZxl43ZHuugRQXxqHadwsU3WYQwFwEjfMQ/s1600/Screenshot%202024-09-12%20204037.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Key Takeaway&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;The Memento pattern is useful for implementing undo/redo functionality by saving different states of an object at different points in time.&lt;/li&gt;&lt;li&gt;The &lt;b&gt;Caretaker&lt;/b&gt; stores &lt;b&gt;Memento&lt;/b&gt; objects without needing to understand their contents.&lt;/li&gt;&lt;li&gt;The &lt;b&gt;Originator&lt;/b&gt; can use a &lt;b&gt;Memento&lt;/b&gt; to restore its state at any given point.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;This pattern helps to manage the internal state of complex objects in a clean and effective manner without exposing internal details to other classes.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/DesignPatterns&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;Memento Design Pattern&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/1785823957360286883/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/memento-design-pattern-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1785823957360286883'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1785823957360286883'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/memento-design-pattern-in-c.html' title='Memento Design Pattern in C#'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgd7dvwQXLzRff9pQ56_-iRd9_CQkxq5Z1OmB5-kjFHk61kT4MaS1QpWjw7qo_Sc0qvRXqaAYu_dBsAh7tMBw-_cbokN1ZiXSMgUVIDtimhA3uTzOJGHorlUPrR3-fsPb7wRoPT1h9_Ui8HC9-B0UFPeA8mIcZxl43ZHuugRQXxqHadwsU3WYQwFwEjfMQ/s72-c/Screenshot%202024-09-12%20204037.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-1233615863330235035</id><published>2024-09-10T17:30:00.005+05:30</published><updated>2024-11-11T02:06:14.736+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Behavioral Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Iterator Design Pattern"/><title type='text'>Iterator Design Pattern in C#</title><content type='html'>&lt;p&gt;The &lt;b&gt;Iterator Design Pattern&lt;/b&gt; is a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/design-pattern.html&quot; target=&quot;_blank&quot;&gt;behavioral design pattern&lt;/a&gt; that allows sequential access to the elements of an aggregate object (i.e., collection) without exposing its underlying representation. That means using the Iterator Design Pattern, we can access the elements of a collection sequentially without knowing its internal representations. This pattern provides a uniform interface for traversing different data structures.&lt;/p&gt;
&lt;p&gt;The collections in C#, like &lt;b&gt;List&lt;/b&gt;, &lt;b&gt;ArrayList&lt;/b&gt;, &lt;b&gt;Array&lt;/b&gt;, etc., are containers containing many objects. In object-oriented programming, the &lt;b&gt;iterator pattern&lt;/b&gt; is a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/design-pattern.html&quot; target=&quot;_blank&quot;&gt;design pattern&lt;/a&gt; in which an iterator is used to traverse a container and access the elements of the container.&lt;/p&gt;
&lt;h2&gt;Components of Iterator Pattern&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Iterator:&lt;/strong&gt; The interface that defines the methods for traversing the collection.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Concrete Iterator:&lt;/strong&gt; The class that implements the iterator interface and performs the actual traversal.&lt;/li&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
  &lt;li&gt;&lt;strong&gt;Aggregate:&lt;/strong&gt; The interface for the collection that provides a method to create an iterator.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Concrete Aggregate:&lt;/strong&gt; The class that implements the aggregate interface and returns an instance of the concrete iterator.&lt;/li&gt;&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example Implementation in C#&lt;/h2&gt;
&lt;p&gt;Let&#39;s create a simple example using the Iterator Pattern. We’ll define a custom collection called BookCollection that holds a list of Book objects. We will implement an iterator to traverse the collection.&lt;/p&gt;
&lt;b&gt;Define Book Class&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace IteratorDesignPattern.Model
{
    public class Book
    {
        public string Title { get; }
        public string Author { get; }

        public Book(string title, string author)
        {
            Title = title;
            Author = author;
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Define the IIterator interface&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace IteratorDesignPattern.Iterator
{
    public interface IIterator&amp;lt;T&amp;gt;
    {
        bool HasNext();
        T Next();
    }
}
&lt;/pre&gt;
&lt;b&gt;Implement the BookIterator class&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using IteratorDesignPattern.Model;

namespace IteratorDesignPattern.Iterator
{
    public class BookIterator : IIterator&amp;lt;Book&amp;gt;
    {
        private readonly List&amp;lt;Book&amp;gt; _books;
        private int _position = 0;

        public BookIterator(List&amp;lt;Book&amp;gt; books)
        {
            _books = books;
        }

        public bool HasNext()
        {
            return _position &amp;lt; _books.Count;
        }

        public Book Next()
        {
            if (!HasNext())
            {
                return null;
            }

            return _books[_position++];
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Define the IAggregate interface&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using IteratorDesignPattern.Iterator;

namespace IteratorDesignPattern.Aggregator
{
    public interface IAggregate&amp;lt;T&amp;gt;
    {
        IIterator&amp;lt;T&amp;gt; CreateIterator();
    }
}
&lt;/pre&gt;
&lt;b&gt;Implement the BookCollection class&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using IteratorDesignPattern.Iterator;
using IteratorDesignPattern.Model;

namespace IteratorDesignPattern.Aggregator
{
    public class BookCollection : IAggregate&amp;lt;Book&amp;gt;
    {
        private readonly List&amp;lt;Book&amp;gt; _books = new List&amp;lt;Book&amp;gt;();

        public void AddBook(Book book)
        {
            _books.Add(book);
        }

        public IIterator&amp;lt;Book&amp;gt; CreateIterator()
        {
            return new BookIterator(_books);
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Using the Iterator(Program.cs)&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
using IteratorDesignPattern.Aggregator;
using IteratorDesignPattern.Iterator;
using IteratorDesignPattern.Model;

BookCollection bookCollection = new BookCollection();
bookCollection.AddBook(new Book(&quot;Do Epic Shit&quot;, &quot;Ankur Wariko&quot;));
bookCollection.AddBook(new Book(&quot;To Kill a Mockingbird&quot;, &quot;Harper Lee&quot;));
bookCollection.AddBook(new Book(&quot;1984&quot;, &quot;George Orwell&quot;));

IIterator&amp;lt;Book&amp;gt; iterator = bookCollection.CreateIterator();

while (iterator.HasNext())
{
    Book book = iterator.Next();
    Console.WriteLine($&quot;{book.Title} by {book.Author}&quot;);
}
Console.ReadLine();
&lt;/pre&gt;

&lt;h2&gt;Output&lt;/h2&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_vtyiCdE-_iyrtBTF-mKarxegZFgG0PBn9qPrxhzjaFigm6p1u84xyds3yFYqEUUuIwbhU1ZEMC3lJsNArYabm9mU-a54jVHX-dLku99877p4EWq0-G66nF8lS1KdVSti9ZFNje92Mhk7hpEqFY4ZNJQ1jvNUq5P1l5jVfXQHVFYkJarZPH3xWVZUzQM/s1600/Screenshot%202024-09-08%20105134.png&quot; style=&quot;display: block; padding: 1em 0; text-align: center; clear: left; float: left;&quot;&gt;&lt;img alt=&quot;Iterator Design Pattern in C#&quot; border=&quot;0&quot; data-original-height=&quot;155&quot; data-original-width=&quot;540&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_vtyiCdE-_iyrtBTF-mKarxegZFgG0PBn9qPrxhzjaFigm6p1u84xyds3yFYqEUUuIwbhU1ZEMC3lJsNArYabm9mU-a54jVHX-dLku99877p4EWq0-G66nF8lS1KdVSti9ZFNje92Mhk7hpEqFY4ZNJQ1jvNUq5P1l5jVfXQHVFYkJarZPH3xWVZUzQM/s1600/Screenshot%202024-09-08%20105134.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;h2 style=&quot;clear: both;&quot;&gt;Explanation&lt;/h2&gt;
&lt;ol&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;Book Class:&lt;/strong&gt; Represents a book with a title and an author.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;IIterator Interface:&lt;/strong&gt; Defines the methods &lt;b&gt;HasNext&lt;/b&gt; (to check if there are more elements) and &lt;b&gt;Next&lt;/b&gt; (to get the next element).&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;BookIterator Class:&lt;/strong&gt; Implements the &lt;b&gt;IIterator&lt;/b&gt; interface. It maintains the current position in the collection and provides methods to traverse the list of books.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;IAggregate Interface:&lt;/strong&gt; Declares a method &lt;b&gt;CreateIterator&lt;/b&gt; to return an iterator for the collection.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;BookCollection Class:&lt;/strong&gt; Implements the &lt;b&gt;IAggregate&lt;/b&gt; interface and provides a way to add books to the collection. It also returns an iterator to traverse the books.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;strong&gt;Using the Iterator:&lt;/strong&gt; In &lt;b&gt;Program.cs&lt;/b&gt; we use the iterator to traverse the &lt;b&gt;BookCollection&lt;/b&gt;. It prints each book&#39;s title and author.&lt;/p&gt;&lt;/li&gt;&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Benefits of the Iterator Pattern&lt;/h2&gt;
&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Encapsulation:&lt;/strong&gt; The Iterator pattern hides the internal structure of the collection, allowing you to traverse it without exposing its implementation details.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Flexibility:&lt;/strong&gt; You can traverse different types of collections using the same interface, making your code more reusable.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Separation of Concerns:&lt;/strong&gt; By separating the collection and the traversal logic, the pattern promotes cleaner code and better maintainability.&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;Iterator pattern&lt;/b&gt; is a powerful tool for managing collections in a flexible and reusable manner. By implementing this pattern in C#, you can simplify the traversal of complex collections and keep your codebase clean and maintainable.&lt;/p&gt;
&lt;p&gt;The full source code is available here:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/DesignPatterns&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;iterator design pattern example&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/1233615863330235035/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/iterator-design-pattern-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1233615863330235035'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1233615863330235035'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/iterator-design-pattern-in-c.html' title='Iterator Design Pattern in C#'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_vtyiCdE-_iyrtBTF-mKarxegZFgG0PBn9qPrxhzjaFigm6p1u84xyds3yFYqEUUuIwbhU1ZEMC3lJsNArYabm9mU-a54jVHX-dLku99877p4EWq0-G66nF8lS1KdVSti9ZFNje92Mhk7hpEqFY4ZNJQ1jvNUq5P1l5jVfXQHVFYkJarZPH3xWVZUzQM/s72-c/Screenshot%202024-09-08%20105134.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-156446101383693839</id><published>2024-09-09T17:30:00.011+05:30</published><updated>2024-11-11T02:06:26.003+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Behavioral Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Interpreter Design Pattern"/><title type='text'>Interpreter Design Pattern in C#</title><content type='html'>&lt;p&gt;The &lt;b&gt;Interpreter Design Pattern&lt;/b&gt; is a &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/design-pattern.html&quot; target=&quot;_blank&quot;&gt;behavioral design pattern&lt;/a&gt; that defines a grammatical representation for a language and provides an interpreter to deal with this grammar. This pattern is particularly useful for designing simple languages or interpreting expressions.&lt;/p&gt;
&lt;h2&gt;When to Use the Interpreter Pattern&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;When you have a simple language to interpret.&lt;/li&gt;
&lt;li&gt;When you need to interpret expressions in a language.&lt;/li&gt;
&lt;li&gt;When the grammar of the language is relatively simple and stable.&lt;/li&gt;
&lt;/ul&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;h2&gt;Components of Interpreter Design Pattern&lt;/h2&gt;
&lt;p&gt;The Interpreter pattern involves the following components:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Abstract Expression&lt;/strong&gt;: Declares an abstract &lt;b&gt;Interpret&lt;/b&gt; method.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Terminal Expression&lt;/strong&gt;: Implements the &lt;b&gt;Interpret&lt;/b&gt; method for terminal symbols in the grammar.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Non-Terminal Expression&lt;/strong&gt;: Implements the &lt;b&gt;Interpret&lt;/b&gt; method for non-terminal symbols in the grammar.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Context&lt;/strong&gt;: Contains information that’s global to the interpreter.&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example in C#: Simple Arithmetic Interpreter&lt;/h2&gt;
&lt;p&gt;Let’s create a simple arithmetic interpreter that can evaluate expressions like “3 + 5 - 2”.&lt;/p&gt;
&lt;b&gt;Define the Abstract Expression&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace InterpreterPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Abstract Expression
    /// &amp;lt;/summary&amp;gt;
    public abstract class Expression
    {
        public abstract int Interpret();
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Define Terminal Expressions&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace InterpreterPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Terminal Expression
    /// &amp;lt;/summary&amp;gt;
    public class NumberExpression : Expression
    {
        private int _number;

        public NumberExpression(int number)
        {
            _number = number;
        }

        public override int Interpret()
        {
            return _number;
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Define Non-Terminal Expressions&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// Add Expression
namespace InterpreterPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Non-Terminal Expression
    /// &amp;lt;/summary&amp;gt;
    public class AddExpression : Expression
    {
        private Expression _leftExpression;
        private Expression _rightExpression;

        public AddExpression(Expression leftExpression, Expression rightExpression)
        {
            _leftExpression = leftExpression;
            _rightExpression = rightExpression;
        }

        public override int Interpret()
        {
            return _leftExpression.Interpret() + _rightExpression.Interpret();
        }
    }
}

//Subtract Expression
namespace InterpreterPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Non-Terminal Expression
    /// &amp;lt;/summary&amp;gt;
    public class SubtractExpression : Expression
    {
        private Expression _leftExpression;
        private Expression _rightExpression;

        public SubtractExpression(Expression leftExpression, Expression rightExpression)
        {
            _leftExpression = leftExpression;
            _rightExpression = rightExpression;
        }

        public override int Interpret()
        {
            return _leftExpression.Interpret() - _rightExpression.Interpret();
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Define the Context&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
namespace InterpreterPattern
{
    /// &amp;lt;summary&amp;gt;
    /// Context
    /// &amp;lt;summary&amp;gt;
    public class Context
    {
        private Dictionary&amp;lt;string, int&amp;gt; _variables;

        public Context()
        {
            _variables = new Dictionary&amp;lt;string, int&amp;gt;();
        }

        public int GetVariable(string name)
        {
            return _variables[name];
        }

        public void SetVariable(string name, int value)
        {
            _variables[name] = value;
        }
    }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Client Code(Program.cs)&lt;/b&gt;
&lt;pre class=&quot;brush:csharp;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
// Example: (3 + 5) - 2
using InterpreterPattern;

Expression expression = new SubtractExpression(
    new AddExpression(
        new NumberExpression(3),
        new NumberExpression(5)
    ),
    new NumberExpression(2)
);

Console.WriteLine($&quot;Result: {expression.Interpret()}&quot;);
Console.WriteLine();
&lt;/pre&gt;
&lt;h2&gt;Explanation&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;NumberExpression&lt;/strong&gt;: Represents numbers in the expression.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;AddExpression&lt;/strong&gt;: Represents addition operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SubtractExpression&lt;/strong&gt;: Represents subtraction operations.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Context&lt;/strong&gt;: Holds any global information needed by the interpreter (not used in this simple example).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;InterpreterClient&lt;/strong&gt;: Constructs the expression tree and interprets it.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;Interpreter Design Pattern&lt;/b&gt; is a powerful tool for evaluating expressions defined by a formal grammar. While this example demonstrates arithmetic operations, the pattern can be extended to handle more complex languages and operations.&lt;/p&gt;
&lt;p&gt;By structuring your code using the Interpreter pattern, you can keep the logic for interpreting each type of expression encapsulated within its own class, leading to a clean and maintainable design.&lt;/p&gt;
&lt;p&gt;The full source code is available here:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/MDubey87/DesignPatterns&quot; target=&quot;_blank&quot;&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;img alt=&quot;Interpreter Design Pattern in C#&quot; border=&quot;0&quot; width=&quot;150&quot; data-original-height=&quot;57&quot; data-original-width=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s320/GithubIcon.png&quot;/&gt;&lt;/div&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;
</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/156446101383693839/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/interpreter-design-pattern-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/156446101383693839'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/156446101383693839'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/interpreter-design-pattern-in-c.html' title='Interpreter Design Pattern in C#'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiuX5ChrNZeHPqNKO1xA6T4Gj45tGTaa_yH8zEvYkccLmL1uNtmIX09YLmDhO0qTM233ezokBlx7Fl377GrkL7w9q0Xn7qEcsabRSkXV0YHbrgI4sRqCRth6G8Cawdq6sCL7wV0nD412QUg9d3NzFwyiNqTA1BwNZaCracjFWvGTQ-ABYpjLgV63XzZgQ/s72-c/GithubIcon.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-8610110905700719759</id><published>2024-09-04T17:30:00.002+05:30</published><updated>2024-09-05T09:08:56.373+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Route Gaurd"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Routing"/><title type='text'>Route Guards in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Route Guards in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;p&gt;When building &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular applications&lt;/a&gt;, managing access to different routes is crucial for both security and user experience. &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; provides a robust mechanism called &lt;b&gt;Route Guards&lt;/b&gt; to control navigation. Let’s dive into what &lt;b&gt;Route Guards&lt;/b&gt; are, the different types available, and how to implement them with examples.&lt;/p&gt;

&lt;h2&gt;What are Route Guards?&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Route Guards&lt;/b&gt; are interfaces that allow you to control the navigation to and from routes in your &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; application. They help you decide whether a user can access a particular route or not. There are several types of Route Guards:&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;CanActivate:&lt;/b&gt; Determines if a route can be activated.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;CanActivateChild:&lt;/b&gt; Determines if child routes can be activated.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;CanDeactivate:&lt;/b&gt; Determines if a route can be deactivated.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;CanLoad:&lt;/b&gt; Determines if a module can be loaded.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;CanMatch:&lt;/b&gt; Determines if a route can be matched.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Implementing CanActivate Guard&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;CanActivate&lt;/b&gt; guard is used to check if a user can navigate to a route. Here’s an example where we use an authentication service to check if the user is logged in.&lt;/p&gt;

&lt;b&gt;Step 1: Create the Auth Service&lt;/b&gt;
&lt;p&gt;First, create an authentication service that will handle the login logic.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class AuthService {
  private isLoggedIn = false;

  login() {
    this.isLoggedIn = true;
  }

  logout() {
    this.isLoggedIn = false;
  }

  isAuthenticated(): boolean {
    return this.isLoggedIn;
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 2: Create the CanActivate Guard&lt;/b&gt;
&lt;p&gt;Next, create the guard that implements the &lt;b&gt;CanActivate&lt;/b&gt; interface.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from &#39;@angular/router&#39;;
import { AuthService } from &#39;./auth.service&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      this.router.navigate([&#39;/login&#39;]);
      return false;
    }
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 3: Apply the Guard to Routes&lt;/b&gt;
&lt;p&gt;Finally, apply the guard to the routes in your routing module.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;
import { HomeComponent } from &#39;./home/home.component&#39;;
import { DashboardComponent } from &#39;./dashboard/dashboard.component&#39;;
import { AuthGuard } from &#39;./auth.guard&#39;;

const routes: Routes = [
  { path: &#39;&#39;, component: HomeComponent },
  { path: &#39;dashboard&#39;, component: DashboardComponent, canActivate: [AuthGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Other Types of Guards&lt;/h2&gt;
&lt;b&gt;CanActivateChild&lt;/b&gt;
&lt;p&gt;This guard works similarly to CanActivate but applies to child routes.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;
import { CanActivateChild } from &#39;@angular/router&#39;;
import { AuthService } from &#39;./auth.service&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class AuthChildGuard implements CanActivateChild {

  constructor(private authService: AuthService) {}

  canActivateChild(): boolean {
    return this.authService.isAuthenticated();
  }
}
&lt;/pre&gt;
&lt;b&gt;CanDeactivate&lt;/b&gt;
&lt;p&gt;This guard is used to prevent users from leaving a route if certain conditions are not met, such as unsaved changes.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;
import { CanDeactivate } from &#39;@angular/router&#39;;
import { Observable } from &#39;rxjs&#39;;

export interface CanComponentDeactivate {
  canDeactivate: () =&gt; Observable&amp;lt;boolean&amp;gt; | Promise&amp;lt;boolean&amp;gt; | boolean;
}

@Injectable({
  providedIn: &#39;root&#39;
})
export class CanDeactivateGuard implements CanDeactivate&amp;lt;CanComponentDeactivate&amp;gt; {

  canDeactivate(component: CanComponentDeactivate): Observable&amp;lt;boolean&amp;gt; | Promise&amp;lt;boolean&amp;gt; | boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}
&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Route Guards in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html#google_vignette&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; are powerful tools for managing access to different parts of your application. By using guards like &lt;b&gt;CanActivate&lt;/b&gt;, &lt;b&gt;CanActivateChild&lt;/b&gt;, and &lt;b&gt;CanDeactivate&lt;/b&gt;, you can enhance the security and user experience of your app. Implementing these guards is straightforward and can be customized to fit your specific needs.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/8610110905700719759/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/route-guards-in-angular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8610110905700719759'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8610110905700719759'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/route-guards-in-angular.html' title='Route Guards in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-8015689010683894431</id><published>2024-09-03T17:30:00.000+05:30</published><updated>2024-09-03T17:30:00.327+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Service"/><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection"/><title type='text'>Lifecycle of an Angular service</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Lifecycle of an Angular service&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;Understanding the lifecycle of an &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; service is crucial for effectively managing dependencies and ensuring optimal performance in your application. Here’s a breakdown of the lifecycle of an &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; service:&lt;/p&gt;

&lt;b&gt;1. Creation&lt;/b&gt;
&lt;p&gt;When a service is first requested by a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/07/angular-understanding-directives-in.html&quot; target=&quot;_blank&quot;&gt;directive&lt;/a&gt;, or another service, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;Angular’s dependency injection&lt;/a&gt; system creates an instance of the service. This happens only once if the service is provided at the root level or a module level, ensuring a singleton instance.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Injectable({
  providedIn: &#39;root&#39;,
})
export class MyService {
  constructor() {
    console.log(&#39;MyService instance created&#39;);
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;2. Injection&lt;/b&gt;
&lt;p&gt;The created instance is then injected into the requesting &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/07/angular-understanding-directives-in.html&quot; target=&quot;_blank&quot;&gt;directive&lt;/a&gt;, or service. This is done through the constructor of the class where the service is needed.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Component({
  selector: &#39;app-my-component&#39;,
  template: `&lt;p&gt;{{ message }}&lt;/p&gt;`,
})
export class MyComponent {
  message: string;

  constructor(private myService: MyService) {
    this.message = this.myService.getMessage();
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;3. Usage&lt;/b&gt;
&lt;p&gt;The methods and properties of the service are used by the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/07/angular-understanding-directives-in.html&quot; target=&quot;_blank&quot;&gt;directive&lt;/a&gt;, or another service. This is where the main functionality of the service is utilized.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Injectable({
  providedIn: &#39;root&#39;,
})
export class MyService {
  getMessage() {
    return &#39;Hello from MyService!&#39;;
  }
}
&lt;/pre&gt;
&lt;b&gt;4. Destruction&lt;/b&gt;
&lt;p&gt;&lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; does not explicitly destroy services. Instead, services are subject to JavaScript’s garbage collection. When there are no more references to the service instance, it becomes eligible for garbage collection. This typically happens when the component or module that requested the service is destroyed.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Key Points to Remember&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Singleton Services:&lt;/b&gt; When a service is provided at the root level (providedIn: &#39;root&#39;), it is a singleton, meaning only one instance of the service exists throughout the application.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Scoped Services:&lt;/b&gt; When a service is provided at a module or component level, it can have multiple instances, each scoped to the module or component where it is provided.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Lazy Loading:&lt;/b&gt; Services provided in lazy-loaded modules are created only when the module is loaded, which can help optimize performance by loading services only when needed.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example Scenario&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;App Initialization:&lt;/b&gt; The application starts, and no services are instantiated yet.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Component Request:&lt;/b&gt; A component requests a service.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Service Creation:&lt;/b&gt; Angular’s DI system creates an instance of the service.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Service Injection:&lt;/b&gt; The service instance is injected into the component.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Service Usage:&lt;/b&gt; The component uses the service’s methods and properties.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Component Destruction:&lt;/b&gt; When the component is destroyed, the service instance remains if it is a singleton. If the service is scoped to the component, it becomes eligible for garbage collection.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding this lifecycle helps in designing services that are efficient, reusable, and maintainable.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/8015689010683894431/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/lifecycle-of-angular-service.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8015689010683894431'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/8015689010683894431'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/lifecycle-of-angular-service.html' title='Lifecycle of an Angular service'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-4822772881016379968</id><published>2024-09-02T17:30:00.015+05:30</published><updated>2024-09-02T17:30:00.251+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection"/><title type='text'>Hierarchical Dependency Injection in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Hierarchical Dependency Injection in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;Hierarchical Dependency Injection (DI) in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; is a powerful feature that allows you to control the scope and lifetime of services. It enables you to create a hierarchy of injectors, where each injector can provide its own set of &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;dependencies&lt;/a&gt;. This hierarchy mirrors the component tree, allowing for fine-grained control over which services are available to which parts of your application.&lt;/p&gt;

&lt;h2&gt;How Hierarchical Dependency Injection Works?&lt;/h2&gt;
&lt;p&gt;In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, every component has its own injector, and these injectors form a hierarchy. The root injector is created when the application starts, and child injectors are created for each &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;. When a component requests a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;dependency&lt;/a&gt;, Angular starts at the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component’s&lt;/a&gt; injector and works its way up the hierarchy until it finds a provider for the requested &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;dependency&lt;/a&gt;.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Example&lt;/b&gt;
&lt;p&gt;Let’s look at an example to understand how hierarchical &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;DI&lt;/a&gt;works.&lt;/p&gt;

&lt;b&gt;Step 1: Create a Service&lt;/b&gt;
&lt;p&gt;First, we’ll create a simple service.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 2: Create Components&lt;/b&gt;
&lt;p&gt;Next, we’ll create a parent &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt;  and a child &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; .&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component } from &#39;@angular/core&#39;;
import { LoggerService } from &#39;./logger.service&#39;;

@Component({
  selector: &#39;app-parent&#39;,
  template: `
    &amp;lt;h1&amp;gt;Parent Component&amp;lt;/h1&amp;gt;
    &amp;lt;app-child&amp;gt;&amp;lt;/app-child&amp;gt;
  `,
  providers: [LoggerService],
})
export class ParentComponent {
  constructor(private logger: LoggerService) {
    this.logger.log(&#39;Parent Component Initialized&#39;);
  }
}

@Component({
  selector: &#39;app-child&#39;,
  template: `&amp;lt;h2&amp;gt;Child Component&amp;lt;/h2&amp;gt;`,
})
export class ChildComponent {
  constructor(private logger: LoggerService) {
    this.logger.log(&#39;Child Component Initialized&#39;);
  }
}
&lt;/pre&gt;
&lt;p&gt;In this example, the &lt;b&gt;ParentComponent&lt;/b&gt; provides the &lt;b&gt;LoggerService&lt;/b&gt;. The &lt;b&gt;ChildComponent&lt;/b&gt; does not provide the &lt;b&gt;LoggerService&lt;/b&gt;, so it will use the instance provided by the &lt;b&gt;ParentComponent&lt;/b&gt;.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 3: Register Components in a Module&lt;/b&gt;
&lt;p&gt;Finally, we’ll register the components in a module.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { BrowserModule } from &#39;@angular/platform-browser&#39;;
import { AppComponent } from &#39;./app.component&#39;;
import { ParentComponent } from &#39;./parent.component&#39;;
import { ChildComponent } from &#39;./child.component&#39;;

@NgModule({
  declarations: [AppComponent, ParentComponent, ChildComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
})
export class AppModule {}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Key Points&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Injector Hierarchy:&lt;/b&gt; Each component has its own injector, forming a hierarchy that mirrors the component tree.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Provider Scope:&lt;/b&gt; Providers can be registered at different levels (root, module, component), controlling the scope and lifetime of services.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Dependency Resolution&lt;/b&gt;: Angular starts at the component’s injector and works its way up the hierarchy to resolve dependencies.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Benefits of Hierarchical Dependency Injection&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Scoped Services:&lt;/b&gt; You can create services that are scoped to specific parts of your application, improving modularity and encapsulation.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Optimized Performance:&lt;/b&gt; By limiting the scope of services, you can reduce memory usage and improve performance.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Flexible Configuration:&lt;/b&gt; Different parts of your application can use different configurations of the same service.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Hierarchical DI is a powerful feature that allows you to build scalable and maintainable Angular applications by providing fine-grained control over service instances and their lifetimes.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/4822772881016379968/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/hierarchical-dependency-injection-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4822772881016379968'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4822772881016379968'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/09/hierarchical-dependency-injection-in.html' title='Hierarchical Dependency Injection in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-4787185285435371839</id><published>2024-08-28T17:30:00.003+05:30</published><updated>2024-09-01T09:35:23.740+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Providers"/><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection"/><title type='text'>Difference between providedIn and providers array</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Difference between providedIn and providers array&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h2&gt;providedIn&lt;/h2&gt;
&lt;p&gt;The &lt;b&gt;providedIn&lt;/b&gt; property is used within the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-injectable-and-inject.html&quot; target=&quot;_blank&quot;&gt;@Injectable&lt;/a&gt; decorator to specify where the service should be provided. This is a more modern and preferred way to provide services in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Global Scope:&lt;/b&gt; When you use &lt;b&gt;providedIn: &#39;root&#39;&lt;/b&gt;, the service is registered with the root injector, making it a singleton and available throughout the entire application.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Injectable({
  providedIn: &#39;root&#39;,
})
export class MyService {
  constructor() { }
}
&lt;/pre&gt;
&lt;p&gt;
  &lt;b&gt;Feature Module Scope:&lt;/b&gt; You can also specify a feature module to limit the scope of the service.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Injectable({
  providedIn: SomeFeatureModule,
})
export class MyService {
  constructor() { }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;providers Array&lt;/h2&gt;
&lt;p&gt;The providers array is used within the &lt;b&gt;@NgModule&lt;/b&gt; or &lt;b&gt;@Component&lt;/b&gt; &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/02/decorators-in-angular.html&quot; target=&quot;_blank&quot;&gt;decorators&lt;/a&gt; to register services. This method is more traditional and offers more granular control over the scope of the service.&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Module Level:&lt;/b&gt; When you add a service to the providers array in an @NgModule, the service is available to all components declared in that module.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@NgModule({
  providers: [MyService]
})
export class AppModule { }
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;Component Level:&lt;/b&gt; When you add a service to the providers array in a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component’s&lt;/a&gt; decorator, the service is available only to that &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; and its children.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Component({
  selector: &#39;app-my-component&#39;,
  providers: [MyService],
  template: `&amp;lt;p&amp;gt;{{ message }}&amp;lt;/p&amp;gt;`,
})
export class MyComponent {
  constructor(private myService: MyService) { }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Key Differences&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Scope:&lt;/b&gt;
    &lt;ol&gt;&lt;li&gt;&lt;b&gt;providedIn: &#39;root&#39;:&lt;/b&gt; Service is available application-wide.&lt;/li&gt;
      &lt;li&gt;&lt;b&gt;providers array:&lt;/b&gt; Service scope can be limited to a specific module or component.&lt;/li&gt;&lt;/ol&gt;
  &lt;/li&gt;
&lt;li&gt;&lt;b&gt;Singleton:&lt;/b&gt;
  &lt;ol&gt;&lt;li&gt;&lt;b&gt;providedIn: &#39;root&#39;:&lt;/b&gt; Ensures a singleton instance across the entire application.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;providers array:&lt;/b&gt; Can create multiple instances if provided at different levels (e.g., module and component).
    &lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Tree Shaking:&lt;/b&gt;
&lt;ol&gt;&lt;li&gt;&lt;b&gt;providedIn:&lt;/b&gt; Supports tree shaking, meaning unused services can be removed during the build process.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;providers array:&lt;/b&gt; Does not support tree shaking as effectively.&lt;/li&gt;&lt;/ol&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Using &lt;b&gt;providedIn&lt;/b&gt; is generally recommended for its simplicity and efficiency, especially for services that need to be available application-wide. The &lt;b&gt;providers array&lt;/b&gt; is useful when you need more control over the scope and lifecycle of your services.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/4787185285435371839/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/difference-between-providedin-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4787185285435371839'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/4787185285435371839'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/difference-between-providedin-and.html' title='Difference between providedIn and providers array'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-454109411694004526</id><published>2024-08-27T17:30:00.007+05:30</published><updated>2024-08-27T17:30:00.120+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="A gular Providers"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection"/><title type='text'>Understanding Providers in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Providers in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, providers are a fundamental concept that allows you to inject dependencies into your &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;components&lt;/a&gt;, services, and other parts of your application. They play a crucial role in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&#39;s&lt;/a&gt; &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;dependency injection (DI)&lt;/a&gt; system, making it easier to manage and share services across your application.&lt;/p&gt;

&lt;h2&gt;What is a Provider?&lt;/h2&gt;
&lt;p&gt;A provider is an instruction to the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html&quot; target=&quot;_blank&quot;&gt;Angular dependency injection&lt;/a&gt; system on how to obtain a value for a dependency. When you configure a provider, you tell Angular how to create an instance of a service or value that can be injected into &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot;&gt;components&lt;/a&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/07/angular-understanding-directives-in.html&quot;&gt;directives&lt;/a&gt;, &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/07/introduction-to-angular-pipes.html&quot; target=&quot;_blank&quot;&gt;pipes&lt;/a&gt;, or other services.&lt;/p&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Types of Providers&lt;/h2&gt;
  &lt;p&gt;Angular supports several types of providers:&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;1- Class Providers:&lt;/b&gt; The most common type, where you provide a class to be instantiated by the DI system.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class MyService {
  constructor() { }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;p&gt;&lt;b&gt;2- Value Providers:&lt;/b&gt; Use this to provide a simple value.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
const MY_VALUE = { key: &#39;value&#39; };

@NgModule({
  providers: [{ provide: &#39;myValue&#39;, useValue: MY_VALUE }]
})
export class AppModule { }
&lt;/pre&gt;
&lt;p&gt;&lt;b&gt;3- Factory Providers:&lt;/b&gt; Use a factory function to create the value.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
export function myFactory() {
  return new MyService();
}

@NgModule({
  providers: [{ provide: MyService, useFactory: myFactory }]
})
export class AppModule { }
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;p&gt;&lt;b&gt;4- Existing Providers:&lt;/b&gt; Alias an existing provider.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@NgModule({
  providers: [{ provide: MyService, useExisting: AnotherService }]
})
export class AppModule { }
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Where to Provide Services?&lt;/h2&gt;
&lt;p&gt;You can provide services at different levels in your Angular application:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Root Level:&lt;/b&gt; By using the &lt;b&gt;providedIn: &#39;root&#39;&lt;/b&gt; syntax in the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-injectable-and-inject.html&quot; target=&quot;_blank&quot;&gt;@Injectable&lt;/a&gt; decorator, the service is available application-wide.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Module Level:&lt;/b&gt; By adding the service to the providers array in an &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/02/decorators-in-angular.html&quot; target=&quot;_blank&quot;&gt;@NgModule decorator&lt;/a&gt;, the service is available to all &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot;&gt;components&lt;/a&gt; declared in that module.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Component Level:&lt;/b&gt; By adding the service to the providers array in a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot;&gt;components&#39;s&lt;/a&gt; decorator, the service is available only to that &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot;&gt;components&lt;/a&gt; and its children.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example: Using a Service in a Component&lt;/h2&gt;
&lt;p&gt;Here’s a simple example of how to use a service in a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot;&gt;components&lt;/a&gt;:&lt;/p&gt;

&lt;b&gt;Create a Service:&lt;/b&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Injectable({
  providedIn: &#39;root&#39;,
})
export class DataService {
  getData() {
    return &#39;Hello from DataService!&#39;;
  }
}
&lt;/pre&gt;
&lt;b&gt;Inject the Service into a Component:&lt;/b&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@Component({
  selector: &#39;app-my-component&#39;,
  template: `&lt;p&gt;{{ message }}&lt;/p&gt;`,
})
export class MyComponent implements OnInit {
  message: string;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.message = this.dataService.getData();
  }
}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
Providers are a powerful feature in &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; that facilitate dependency injection, making your code more modular, testable, and maintainable. By understanding and utilizing different types of providers, you can effectively manage dependencies in your &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; applications.&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/454109411694004526/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-providers-in-angular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/454109411694004526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/454109411694004526'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-providers-in-angular.html' title='Understanding Providers in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-1953857969493865047</id><published>2024-08-26T17:30:00.004+05:30</published><updated>2024-08-26T17:30:00.120+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Angular Module"/><title type='text'>Understanding Lazy-Loaded Modules in Angular</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Lazy-Loaded Modules in Angular&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;
&lt;b&gt;Lazy loading&lt;/b&gt; is a design pattern in Angular that allows you to load modules only when they are needed, rather than loading all modules upfront. This can significantly improve the performance of your application by reducing the initial load time.&lt;/p&gt;

&lt;h2&gt;What is a Lazy-Loaded Module?&lt;/h2&gt;
&lt;p&gt;A lazy-loaded module is an &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; module that is loaded on demand. Instead of being included in the main bundle, it is loaded asynchronously when the user navigates to a route that requires the module.&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Example:&lt;/b&gt;
&lt;p&gt;Let’s create a simple example to demonstrate lazy loading.&lt;/p&gt;

&lt;b&gt;Step 1: Create a Feature Module&lt;/b&gt;
&lt;p&gt;First, we’ll create a feature module that we want to lazy load.&lt;/p&gt;

&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { FeatureComponent } from &#39;./feature.component&#39;;
import { RouterModule } from &#39;@angular/router&#39;;

@NgModule({
  declarations: [FeatureComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: &#39;&#39;, component: FeatureComponent }
    ])
  ]
})
export class FeatureModule {}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 2: Configure Lazy Loading in the App Routing Module&lt;/b&gt;
&lt;p&gt;Next, we’ll configure the app routing module to lazy load the feature module.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;

const routes: Routes = [
  { path: &#39;feature&#39;, loadChildren: () =&gt; import(&#39;./feature/feature.module&#39;).then(m =&gt; m.FeatureModule) }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
&lt;/pre&gt;
&lt;p&gt;In this example, the &lt;b&gt;FeatureModule&lt;/b&gt; is lazy-loaded when the user navigates to the /feature route.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Impact on Dependency Injection Hierarchy&lt;/h2&gt;
&lt;p&gt;&lt;b&gt;Lazy-loaded&lt;/b&gt; modules have their own injector, which is a child of the root injector. This has several implications for dependency injection:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Scoped Services:&lt;/b&gt; Services provided in a lazy-loaded module are scoped to that module. This means that each lazy-loaded module can have its own instance of a service, separate from the root injector and other lazy-loaded modules.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Service Isolation:&lt;/b&gt; Services provided in a lazy-loaded module are not available to the rest of the application unless explicitly provided at a higher level (e.g., in the root module).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Memory Management: &lt;/b&gt;Lazy loading can help with memory management by loading services only when needed and potentially unloading them when the module is no longer in use.&lt;/li&gt;
&lt;/ul&gt;
&lt;b&gt;Example:&lt;/b&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class RootService {
  constructor() {}
}

@Injectable()
export class LazyService {
  constructor() {}
}
&lt;/pre&gt;
&lt;p&gt;In this example, &lt;b&gt;RootService&lt;/b&gt; is provided at the root level and is available throughout the application. &lt;b&gt;LazyService&lt;/b&gt;, on the other hand, is provided in a lazy-loaded module and is only available within that module.&lt;/p&gt;

&lt;b&gt;Feature Module:&lt;/b&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
@NgModule({
  providers: [LazyService],
  // other module metadata
})
export class FeatureModule {}
&lt;/pre&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Key Points&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Lazy Loading:&lt;/b&gt; Modules are loaded on demand, improving initial load time and performance.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Scoped Services:&lt;/b&gt; Services in lazy-loaded modules are scoped to those modules, allowing for isolated instances.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Injector Hierarchy:&lt;/b&gt; Lazy-loaded modules have their own injectors, which are children of the root injector.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Benefits of Lazy Loading&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Improved Performance:&lt;/b&gt; Reduces the initial load time by loading only the necessary modules.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Modular Architecture:&lt;/b&gt; Encourages a modular architecture by isolating features and their dependencies.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Better Resource Management:&lt;/b&gt; Loads resources only when needed, potentially reducing memory usage.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Lazy loading is a powerful feature in Angular that, when combined with hierarchical dependency injection, allows for efficient and modular application design.
&lt;/p&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/1953857969493865047/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-lazy-loaded-modules-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1953857969493865047'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/1953857969493865047'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-lazy-loaded-modules-in.html' title='Understanding Lazy-Loaded Modules in Angular'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1563380748301069004.post-7111960731612802256</id><published>2024-08-22T17:30:00.002+05:30</published><updated>2024-08-26T09:40:03.158+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Angular"/><category scheme="http://www.blogger.com/atom/ns#" term="Dependency Injection"/><title type='text'>Understanding Angular Dependency Injection</title><content type='html'>&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot; style=&quot;clear: left; float: left; margin-bottom: 0 1em 0 0; margin-right: 1em;&quot;&gt;&lt;img alt=&quot;Angular Dependency Injection&quot; border=&quot;0&quot; data-original-height=&quot;138&quot; data-original-width=&quot;138&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s1600/aGNEW.png&quot;/&gt;&lt;/a&gt;&lt;/div&gt;&lt;p&gt;&lt;b&gt;Dependency Injection (DI)&lt;/b&gt; is a design pattern used to implement &lt;b&gt;IoC (Inversion of Control)&lt;/b&gt;, allowing a class to receive its dependencies from an external source rather than creating them itself. &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular’s&lt;/a&gt; DI system is a powerful feature that makes it easy to manage dependencies and promote code reusability and testability.&lt;/p&gt;

&lt;h2&gt;How Dependency Injection Works in Angular?&lt;/h2&gt;
&lt;p&gt;
In &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt;, DI is used to provide &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;components&lt;/a&gt;, &lt;b&gt;services&lt;/b&gt;, and other classes with the dependencies they need. The &lt;a href=&quot;https://manish4dotnet.blogspot.com/p/angular.html&quot; target=&quot;_blank&quot;&gt;Angular&lt;/a&gt; injector is responsible for creating and managing these dependencies. Here’s a step-by-step explanation of how DI works in Angular:&lt;/p&gt;&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;ul&gt;
  &lt;li&gt;
&lt;b&gt;Providers:&lt;/b&gt; A provider is an object that tells the injector how to create a dependency. Providers can be registered at different levels (module, component, or service).&lt;/li&gt;
  &lt;li&gt;
&lt;b&gt;Injector:&lt;/b&gt; The injector is responsible for creating instances of dependencies and injecting them into the classes that need them.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Tokens:&lt;/b&gt;Tokens are used to uniquely identify a dependency. They can be class types, strings, or injection tokens.&lt;/li&gt;
&lt;/ul&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;h2&gt;Example: Using Dependency Injection in Angular&lt;/h2&gt;
&lt;p&gt;Let’s create a simple example to demonstrate how DI works in Angular.&lt;/p&gt;

&lt;b&gt;Step 1: Create a Service&lt;/b&gt;

&lt;p&gt;First, we’ll create a service that provides some data.&lt;/p&gt;

&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class DataService {
  constructor() {}

  getData() {
    return [&#39;Item1&#39;, &#39;Item2&#39;, &#39;Item3&#39;];
  }
}
&lt;/pre&gt;
&lt;p&gt;In this example, the &lt;b&gt;DataService&lt;/b&gt; class is decorated with &lt;a href=&quot;https://manish4dotnet.blogspot.com/2024/08/understanding-injectable-and-inject.html&quot; target=&quot;_blank&quot;&gt;@Injectable&lt;/a&gt;, making it available for injection throughout the application.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 2: Inject the Service into a Component&lt;/b&gt;

&lt;p&gt;Next, we’ll create a &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&lt;/a&gt; and inject the &lt;b&gt;DataService&lt;/b&gt; into it.&lt;/p&gt;
&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { DataService } from &#39;./data.service&#39;;

@Component({
  selector: &#39;app-data&#39;,
  template: `
    &amp;lt;h1&amp;gt;Data from Service&amp;lt;/h1&amp;gt;
    &amp;lt;ul&amp;gt;
      &amp;lt;li *ngFor=&quot;let item of data&quot;&amp;gt;{{ item }}&amp;lt;/li&amp;gt;
    &amp;lt;/ul&amp;gt;
  `,
})
export class DataComponent implements OnInit {
  data: string[];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.data = this.dataService.getData();
  }
}
&lt;/pre&gt;
&lt;p&gt;In this example, the &lt;b&gt;DataComponent&lt;/b&gt; class has a dependency on &lt;b&gt;DataService&lt;/b&gt;. The &lt;b&gt;DataService&lt;/b&gt; is injected into the &lt;a href=&quot;https://manish4dotnet.blogspot.com/2023/04/angular-component.html&quot; target=&quot;_blank&quot;&gt;component&#39;s&lt;/a&gt; constructor, and its &lt;b&gt;getData&lt;/b&gt; method is called to retrieve data.&lt;/p&gt;
&lt;div id=&quot;adContent&quot; style=&quot;padding-bottom:15px;padding-top:15px&quot;&gt;
  &lt;script async src=&quot;https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1057718374354714&quot;
     crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;ins class=&quot;adsbygoogle&quot;
     style=&quot;display:block; text-align:center;&quot;
     data-ad-layout=&quot;in-article&quot;
     data-ad-format=&quot;fluid&quot;
     data-ad-client=&quot;ca-pub-1057718374354714&quot;
     data-ad-slot=&quot;4432765064&quot;&gt;&lt;/ins&gt;
&lt;script&gt;
     (adsbygoogle = window.adsbygoogle || []).push({});
&lt;/script&gt;
&lt;/div&gt;
&lt;b&gt;Step 3: Register the Service in a Module (if not using providedIn: &#39;root&#39;)&lt;/b&gt;

&lt;p&gt;If you are not using the &lt;b&gt;providedIn: &#39;root&#39;&lt;/b&gt; syntax, you need to register the service in a module.&lt;/p&gt;

&lt;pre class=&quot;brush:javascript;class-name: &#39;divSyntax&#39;&quot; style=&quot;text-align: left;&quot;&gt;
import { NgModule } from &#39;@angular/core&#39;;
import { BrowserModule } from &#39;@angular/platform-browser&#39;;
import { AppComponent } from &#39;./app.component&#39;;
import { DataComponent } from &#39;./data.component&#39;;
import { DataService } from &#39;./data.service&#39;;

@NgModule({
  declarations: [AppComponent, DataComponent],
  imports: [BrowserModule],
  providers: [DataService],
  bootstrap: [AppComponent],
})
export class AppModule {}
&lt;/pre&gt;
&lt;p&gt;In this example, the &lt;b&gt;DataService&lt;/b&gt; is registered in the providers array of the &lt;b&gt;AppModule&lt;/b&gt;.&lt;/p&gt;

&lt;h2&gt;Benefits of Dependency Injection&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;b&gt;Reusability:&lt;/b&gt; Services can be reused across different components.&lt;/li&gt;
  &lt;li&gt;&lt;b&gt;Testability:&lt;/b&gt; Dependencies can be easily mocked or replaced in unit tests.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Maintainability:&lt;/b&gt; Dependencies are managed in a centralized way, making the codebase easier to maintain.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Happy coding!! 😊&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://manish4dotnet.blogspot.com/feeds/7111960731612802256/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/7111960731612802256'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1563380748301069004/posts/default/7111960731612802256'/><link rel='alternate' type='text/html' href='http://manish4dotnet.blogspot.com/2024/08/understanding-angular-dependency.html' title='Understanding Angular Dependency Injection'/><author><name>Manish</name><uri>http://www.blogger.com/profile/07340495073591888692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiM834dvGWfgRXc0lCKbcjhEUZUj2nZAMUFaJ2H0vyAFtKESjoPr20pd48JMR_m_itw6YvNPdFx0g54RBaM5K-fYdXqaaZbo1R8nCQJbv4FmnU22amGz9xFjmMLk85_VUrfwJC-uKNc5ZvrRhzLQ_ALOqSmFEhQBxFSeh3fpMeXet2WqvWuJPePOa6KD8/s72-c/aGNEW.png" height="72" width="72"/><thr:total>0</thr:total></entry></feed>