Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Thursday, 11 December 2025

circuit breaker pattern in .net core

 Below is a clear, interview-ready and practical explanation of the Circuit Breaker pattern in .NET Core, along with real-time examples and code using Polly (the standard library for resilience in .NET).


Circuit Breaker Pattern in .NET Core

What it is

Circuit Breaker is a resilience pattern used to prevent your system from repeatedly calling a failing external service (API/database/message broker).
It protects the system from cascading failures.


🔌 States of Circuit Breaker

State Meaning
Closed Everything works normally (calls allowed).
Open Calls blocked immediately because external service is failing.
Half-Open Allows limited trial calls to see if the service recovered.

⭐ Why we use it

  • To avoid hitting a failing service over & over

  • To prevent resource consumption (threads, CPU, DB connections)

  • To improve latency by quickly failing requests

  • To give time for the external system to recover


📦 Circuit Breaker in .NET Core using Polly

Install package:

dotnet add package Polly.Extensions.Http

✔️ Simple Circuit Breaker Example

services.AddHttpClient("StockApiClient")
    .AddTransientHttpErrorPolicy(policy => 
        policy.CircuitBreakerAsync(
            handledEventsAllowedBeforeBreaking: 3,      // After 3 failures
            durationOfBreak: TimeSpan.FromSeconds(30),  // Keep circuit open for 30 sec
            onBreak: (result, ts) =>
            {
                Console.WriteLine("Circuit opened!");
            },
            onReset: () =>
            {
                Console.WriteLine("Circuit closed!");
            },
            onHalfOpen: () =>
            {
                Console.WriteLine("Circuit half-open: trying test call.");
            }
        ));

Meaning:

  • If API fails 3 times → Circuit goes OPEN

  • For the next 30 seconds → all calls fail immediately

  • After 30 sec → Circuit goes HALF-OPEN

  • If next call succeeds → RESET (Closed)

  • If fails → OPEN again


✔️ Circuit Breaker + Retry (Best Practice)

services.AddHttpClient("PaymentService")
    .AddPolicyHandler(
        HttpPolicyExtensions
            .HandleTransientHttpError()
            .RetryAsync(3) // retry 3 times
    )
    .AddPolicyHandler(
        HttpPolicyExtensions
            .HandleTransientHttpError()
            .CircuitBreakerAsync(5, TimeSpan.FromSeconds(20))
    );

Retry handles intermittent failures.
Circuit Breaker handles persistent failures.


✔️ Using Circuit Breaker in Controller

public class StockController : ControllerBase
{
    private readonly IHttpClientFactory _factory;
    public StockController(IHttpClientFactory factory) => _factory = factory;

    [HttpGet("price/{symbol}")]
    public async Task<IActionResult> GetStockPrice(string symbol)
    {
        var client = _factory.CreateClient("StockApiClient");

        var response = await client.GetAsync($"/api/stock/{symbol}");

        if (!response.IsSuccessStatusCode)
            return StatusCode((int)response.StatusCode, "External service failed");

        var data = await response.Content.ReadAsStringAsync();
        return Ok(data);
    }
}

🎯 Real-Time Scenarios Where You Use Circuit Breaker

1. Payment Gateways

If Razorpay/Stripe API is failing, don’t call them continuously.
Circuit stops the calls.

2. Microservices Architecture

If Order Service relies on Inventory Service and Inventory is down →
stop hammering it; return fallback immediately.

3. Slow database or cache

If Redis/Azure SQL is timing out → circuit opens → API returns quick response instead of long delays.

4. Third-party APIs (SMS, Email, Notification)

Avoid getting throttled or blocked by calling continuously.


📘 How You Answer in Interviews (30-second answer)

“Circuit Breaker is a resilience pattern that prevents the system from making calls to a failing external service.
In .NET Core, we implement it using Polly.
After a defined number of failures, the circuit moves to Open state and blocks all calls for a specified time.
This prevents cascading failures and improves performance.
I generally combine Retry + Circuit Breaker in HttpClient when calling microservices or external systems.”



Wednesday, 7 August 2024

Abstract factory pattern

 namespace ConsoleApp1

{

    public class TestCls

    {

        public delegate void DelGetMessage();

        public delegate void DelMethod(int x, int y);

        public delegate string MyDel(string str);

       public event MyDel myEvent;

        public  TestCls() {

            this.myEvent += new MyDel(WelComeUser);

        }

        public string WelComeUser(string user)

        {

            return "Welcome " + user;

        }

      


        public void GetValue()

        {

            Console.WriteLine("Test");

        }


        public string GetMsg()

        {

            DelGetMessage delGetMessage = new DelGetMessage(GetValue);

            delGetMessage.Invoke();

            return "Teststr";

        }


        public void plus_Method1(int x, int y)

        {

            Console.Write("You are in plus_Method");

            Console.WriteLine(x + y);

        }


        public void subtract_Method2(int x, int y)

        {

            Console.Write("You are in subtract_Method");

            Console.WriteLine(x - y);

        }



    }


    class Student

    {

        public int StudentID { get; set; }

        public String StudentName { get; set; }

        public int Age { get; set; }

    }

}



VehicleCompany vehicleCompany = new TataCompany();
vehicleCompany.Car();
VehicleCompany vehicleCompany2 = new TeslaCompany();
vehicleCompany.Bike();

Friday, 25 May 2018

Thursday, 16 November 2017

StructureMap IOC With ASP.NET MVC 5

Introduction
In this article, we will learn how we can implement StructureMap IOC container / dependency injection in ASP.NET MVC 5. Actually, we have different tools able to ensure inversion of control pattern, like (Unity, Autofac, Ninject, StructureMap, etc…). In this demo, we will see the steps that should be used to perform StructureMap in ASP.NET MVC 5 application.
In this article, we are going to,
  • Create MVC application.
  • Configuring StructureMap IOC.
  • Create repository.
  • Create controller.
 Create your MVC application
Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

ASP.NET
Next, new dialog will pop up for selecting the template. We are going choose MVC template and click OK button.

ASP.NET
Configuring StructureMap IOC
After creating our project, we are going to add StructureMap IOC. For this, right click on References > Manage NuGet Packages, type StrucutreMap.MVC5 in search box, then click on Install button, as shown below.

ASP.NET
You can also get StructureMap by using package manager console and run the following command:
PM> install-package StructureMap.MVC5
After installing StructureMap, from solution explorer we can notice that Dependency Resolution folder has been added, also StructuremapMVC.cs file in App_Start folder.

ASP.NET
The important file which is needed is the DefaultRegistry.cs.
DefaultRegistry.cs 
  1. namespace StructureMapMVC5.DependencyResolution {  
  2.     using Repository;  
  3.     using StructureMap.Configuration.DSL;  
  4.     using StructureMap.Graph;  
  5.   
  6.     public class DefaultRegistry : Registry {  
  7.         #region Constructors and Destructors  
  8.   
  9.         public DefaultRegistry() {  
  10.             Scan(  
  11.                 scan => {  
  12.                     scan.TheCallingAssembly();  
  13.                     scan.WithDefaultConventions();  
  14.                     scan.With(new ControllerConvention());  
  15.                 });  
  16.             For<ICustomerRepository>().Use<CustomerRepository>();  
  17.               
  18.         }  
  19.  
  20.         #endregion  
  21.     }  
  22. }   
In Default Registry class, we are going configure StructureMap container. In fact, we have two way to configure our container - by using explicit registrations or conventional auto registration.
As you can see, in this example we are composing our application object by connecting abstraction (in this case ICustomerRepository) to concrete type (represented by CustomerRepository). To do that, we are using the fluent Api For<ICustomerRepository>().Use<CustomerRepository>() which registers a default instance for a given type.
If you also have more repetitive similar registrations, such registrations are painful. StructureMap provides auto registration and conversion mechanism which is able to register types automatically. This means, the scanner will register the default instance. Whenever you add an additional interface such IEmployeeRepository and a class EmployeeRepository, it’s automatically picked up by the scanner scan.WithDefaultConventions();
Create Repository
ICustomerRepository.cs
  1. using StructureMapMVC5.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace StructureMapMVC5.Repository  
  9. {  
  10.    public interface ICustomerRepository  
  11.     {  
  12.         IEnumerable<Customer> GetCustomers();  
  13.     }  
  14. }  
CustomerRepository.cs 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using StructureMapMVC5.Models;  
  6.   
  7. namespace StructureMapMVC5.Repository  
  8. {  
  9.     public class CustomerRepository : ICustomerRepository  
  10.     {  
  11.         public IEnumerable<Customer> GetCustomers()  
  12.         {  
  13.             var customerData = new List<Customer>()  
  14.             {  
  15.                new Customer() { ID = 1, Name = "Ali", Email = "Ali@gmail.com", Country = "Morocco"},  
  16.                new Customer() { ID = 2, Name = "Amine", Email = "Amine@gmail.com", Country = "Morocco"},  
  17.                new Customer() { ID = 3, Name = "Kumar", Email = "Kumar@gmail.com", Country = "India"},  
  18.                new Customer() { ID = 4, Name = "Messi", Email = "Messi@gmail.com", Country = "Spain"},  
  19.             };  
  20.   
  21.             return customerData;  
  22.         }  
  23.     }  
  24. }   
Create a controller
Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> selecting MVC5 Controller – Empty > click Add.

ASP.NET
Enter Controller name (‘CustomerController’).

ASP.NET
CustomerController.cs 
  1. using StructureMapMVC5.Models;  
  2. using StructureMapMVC5.Repository;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace StructureMapMVC5.Controllers  
  10. {  
  11.     public class CustomerController : Controller  
  12.     {  
  13.         private readonly ICustomerRepository _customerRepository;  
  14.   
  15.         public CustomerController(ICustomerRepository customerRepository)  
  16.         {  
  17.             _customerRepository = customerRepository;  
  18.         }  
  19.   
  20.         // GET: Customer  
  21.         public ActionResult Index()  
  22.         {  
  23.            var customers = _customerRepository.GetCustomers();  
  24.   
  25.             return View(customers);  
  26.         }  
  27.     }  
  28. }   
As you can see, I am creating Index() action that returns customers list from GetCustomers() method.
Adding View
It’s easy to do. Just right click on Index() action, select Add View and dialog will pop up; write a name for your View and finally, click Add.

ASP.NET 
  1. @model IEnumerable<StructureMapMVC5.Models.Customer>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Name)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Email)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.Country)  
  22.         </th>  
  23.         <th></th>  
  24.     </tr>  
  25.   
  26. @foreach (var item in Model) {  
  27.     <tr>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.Name)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Email)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.Country)  
  36.         </td>  
  37.         <td>  
  38.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  39.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  40.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  41.         </td>  
  42.     </tr>  
  43. }  
  44.   
  45. </table>   
Output
Now, you can run your application. Let’s see the output.

ASP.NET

Recent Post

how to control duplicate order