<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohammad Hasan Hosseini on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Hasan Hosseini on Medium]]></description>
        <link>https://medium.com/@m2hweb86?source=rss-e28028b31f14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v-PKNzWS8cuBC8adJg9S4A.jpeg</url>
            <title>Stories by Mohammad Hasan Hosseini on Medium</title>
            <link>https://medium.com/@m2hweb86?source=rss-e28028b31f14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 01:19:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m2hweb86/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[FeatureFusion: an engineering lab that extracts reusable .NET building blocks]]></title>
            <link>https://medium.com/@m2hweb86/featurefusion-an-engineering-lab-that-extracts-reusable-net-building-blocks-28152cafafb9?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/28152cafafb9</guid>
            <category><![CDATA[mediator]]></category>
            <category><![CDATA[telemetry]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 10:38:09 GMT</pubDate>
            <atom:updated>2026-09-01T20:28:19.434Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I did not start with NuGet packages. I started with recurring problems in real applications, built a public lab to work on them, and extracted a BuildingBlock only when the implementation earned a boundary.</em></p><p>I have spent about sixteen years building software.</p><p>Over that time the languages and hosts changed. The recurring problems did not. Messaging and command dispatch. Pagination that does not fall over on a deep page. Observability that actually leaves the process. Idempotency. Caching. Outbox and inbox. Rate limiting. Infrastructure composition. Later, MCP — the same application logic for a human HTTP client and for a tool host.</p><p>I solved those problems inside production-oriented applications. Then I solved a close cousin of the same problem in the next application. The copy-paste helper worked until the second codebase needed a slightly different contract. Then there were two implementations that looked related and were not.</p><p>The original idea was not “I want five NuGet packages.”</p><p>It was: I have solved many of these problems in real applications. I want one public repository where I can experiment with the ideas, demonstrate them in a running host, write down the architectural decisions, test them, and share the results — especially for technical writing on LinkedIn and elsewhere.</p><p>That repository is <a href="https://github.com/Maxofpower/FeatureFusion">FeatureFusion</a>.</p><p>It started as a personal engineering lab and showcase. A place to make the work observable. Not a framework. Not a pattern catalog. A lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3r8eIrC17wptLLEFMNGstQ.png" /><figcaption><em>The public repository is the showcase. Packages are what left the lab — not the starting point</em></figcaption></figure><h3>The lab grew because the problems kept showing up</h3><p>Once the repository existed, it became the place to put the next recurring problem instead of another private helper.</p><p>Aspire composition. A PostgreSQL catalog. RabbitMQ. Redis. A gateway. Feature flags. MCP tools. OpenTelemetry into a local SigNoz stack. The lab grew quickly because it was useful: I could try an idea, see it in a real request path, and write about what I actually ran — not a slide.</p><p>That growth created a second problem, a good one.</p><p>Some implementations were no longer “demo code in a showcase app.” They had a shape that could live outside FeatureFusion. Keeping them only inside the lab started to hide the contract: dependencies, non-goals, tests, versioning.</p><p>Extraction is a form of architectural validation. A public package cannot hide its API. It cannot hide what it refuses to do. It cannot pretend the host will always look like FeatureFusion.</p><p>So the work gained a second stage. Not a rebrand. A filter.</p><blockquote><em>Build it because a real problem exists. Prove it in an application. Refine the boundary. Test it. Document the trade-offs. Then, if it is reusable enough, extract it into a BuildingBlock.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxDH56lUY3-0bgujzgro1A.png" /><figcaption><em>Useful in one application does not automatically mean ready to become a library.</em></figcaption></figure><h3>What FeatureFusion is — and what it is not</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjqy-6Y5vQGMijbtqoidyQ.png" /><figcaption><em>Showcase application. Then BuildingBlocks. Then MIT NuGet.</em></figcaption></figure><p>FeatureFusion is the engineering lab: a runnable .NET API and Aspire AppHost with PostgreSQL, Redis, RabbitMQ, Memcached, and local SigNoz. Versioned HTTP. MCP in Development.</p><p>BuildingBlocks are the reusable implementations that have earned a package boundary.</p><p>NuGet is the distribution mechanism. MIT on purpose: permissive, independent of FeatureFusion, implementation visible, no proprietary licensing barrier. You can take a package without taking the architecture. That is not legal advice. It is why the packages are licensed the way they are.</p><p>FeatureFusion is not a NuGet collection with a demo bolted on. It is the opposite.</p><p>The packages stay small and focused on purpose. I do not want FeatureFusion to become a framework that dictates how an application must be built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x49BOb4Z5DCyOUQXOcvmw.png" /><figcaption><em>Dashed and in-repo pieces are still part of the lab. They are not NuGet ids</em></figcaption></figure><h3>Implementations that crossed the boundary</h3><p>Five packages are on nuget.org today. They are examples of work that survived the lab long enough to leave it. Versions are the current published versions at the time of writing.</p><p><strong>BuildingBlocks.Mediator 1.1.0</strong> — CQRS Send and an ordered pipeline. net8 / net9 / net10. <a href="https://www.nuget.org/packages/BuildingBlocks.Mediator">https://www.nuget.org/packages/BuildingBlocks.Mediator</a></p><p><strong>BuildingBlocks.Pagination.EntityFrameworkCore 1.0.0</strong> — typed keyset (cursor) paging for EF Core. net8 / net9 / net10. There is no separate BuildingBlocks.Pagination nupkg; the shared IR is bundled in this package. <a href="https://www.nuget.org/packages/BuildingBlocks.Pagination.EntityFrameworkCore">https://www.nuget.org/packages/BuildingBlocks.Pagination.EntityFrameworkCore</a></p><p><strong>BuildingBlocks.Mcp 1.0.0</strong> — deny-by-default MCP tools on the official C# SDK. Does not require Mediator. net8 / net9 / net10. <a href="https://www.nuget.org/packages/BuildingBlocks.Mcp">https://www.nuget.org/packages/BuildingBlocks.Mcp</a></p><p><strong>BuildingBlocks.Telemetry 1.0.2</strong> — config-driven OpenTelemetry from one host call. Not a SigNoz SDK. net8 / net9 / net10. <a href="https://www.nuget.org/packages/BuildingBlocks.Telemetry">https://www.nuget.org/packages/BuildingBlocks.Telemetry</a></p><p><strong>BuildingBlocks.Aspire.Hosting.SigNoz 1.0.0</strong> — local Aspire AppHost SigNoz. net10 only. <a href="https://www.nuget.org/packages/BuildingBlocks.Aspire.Hosting.SigNoz">https://www.nuget.org/packages/BuildingBlocks.Aspire.Hosting.SigNoz</a></p><p>They are separate packages because they have separate reasons to exist. Cursor paging should not drag in a mediator. MCP should not require one. Telemetry exports OTLP to whatever backend you already run. Local SigNoz is an AppHost concern.</p><p>The Dapper pagination adapter is in the repository and is not packed. APIs, caveats, and test matrices live in <a href="https://github.com/Maxofpower/FeatureFusion/tree/main/docs/building-blocks">docs/building-blocks</a>.</p><h3>Extraction example: dispatch became Mediator</h3><p>FeatureFusion needed a controlled way to send commands and queries: handlers from DI, a pipeline the host orders, writes distinct from reads.</p><p>I did not start from “implement the mediator pattern.” I started from dispatch in the application. When the contract settled, it became <a href="https://www.nuget.org/packages/BuildingBlocks.Mediator">BuildingBlocks.Mediator</a>.</p><p>Messages are ICommand, ICommand&lt;T&gt;, or IQuery&lt;T&gt;. No public IRequest. No non-generic IQuery. Call sites prefer ISender.</p><pre>public sealed record CreateOrder(string Product, int Qty) : ICommand&lt;Guid&gt;;</pre><pre>public sealed class CreateOrderHandler : ICommandHandler&lt;CreateOrder, Guid&gt;<br>{<br>    public Task&lt;Guid&gt; Handle(CreateOrder command, CancellationToken ct)<br>        =&gt; Task.FromResult(Guid.NewGuid());<br>}</pre><pre>services.AddMediator(cfg =&gt;<br>{<br>    cfg.RegisterServicesFromAssemblyContaining&lt;CreateOrderHandler&gt;();<br>    cfg.AddOpenBehavior(typeof(ValidationBehavior&lt;,&gt;), order: 0);<br>    cfg.UseTelemetry();<br>    cfg.ValidateOnStartup = true;<br>});</pre><pre>await sender.Send(new CreateOrder(&quot;SKU-1&quot;, 2), ct);</pre><p>The pipeline is host-owned. Validation is a behavior you register. UseTelemetry() is optional. v1 has no Publish / INotification — the lab’s event bus is a sibling, not a mediator notification channel.</p><p>In FeatureFusion, order creation and product listing use the same ISender a host would install. That is the extraction test: the lab did not keep a private second implementation.</p><h3>Extraction example: a catalog that could not live on OFFSET</h3><p>Skip((page - 1) * size) is easy to write. On a deep page it asks the database to walk past rows it will throw away.</p><pre>page 1  → skip 0<br>page 2  → skip 20<br>page N  → skip (N − 1) × 20</pre><p>Keyset continues from the last values you already saw:</p><pre>last row:<br>  Price = 19.99<br>  Id    = 1042</pre><pre>next page:<br>  seek from (19.99, 1042)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FpA9DBeIIc7WNK6PvoFUg.png" /><figcaption><em>The diagram is the concept. It is not a claim about every database engine.</em></figcaption></figure><p>The lab needed stable next-page over a real PostgreSQL products catalog — not an in-memory list. Typed sort keys, composite order, unique Id as tie-breaker, forward and backward cursors, first-page total count, opaque cursors, cancellation, EF Core, and an in-repo Dapper adapter. PostgreSQL keeps QueryHint.None.</p><p>When that contract settled, it became <a href="https://www.nuget.org/packages/BuildingBlocks.Pagination.EntityFrameworkCore">BuildingBlocks.Pagination.EntityFrameworkCore</a> — not a package named BuildingBlocks.Pagination.</p><pre>var key = SortKey.For&lt;Product&gt;()<br>    .By(p =&gt; p.Price)<br>    .ThenByUnique(p =&gt; p.Id);</pre><pre>var page = await db.Products<br>    .AsNoTracking()<br>    .TagWith(&quot;products.list&quot;)<br>    .ToCursorPageAsync(new CursorRequest(cursor, 20), key);</pre><p>CursorRequest is positional: cursor, limit, optional PageDirection when the cursor is empty. No page index. Send cursors back unchanged.</p><p>HMAC, nullable-slot rules, and provider notes stay in the <a href="https://github.com/Maxofpower/FeatureFusion/blob/main/docs/building-blocks/pagination.md">pagination docs</a>.</p><p>The showcase is GET /api/v2/products-page on that PostgreSQL catalog (~1000 seeded rows). The same GetProductsQuery drives GET, POST, MVC, Dapper, and MCP products.list.</p><pre>GET /api/v2/products-page?limit=20&amp;sortBy=Price&amp;sortDirection=Ascending<br>GET /api/v2/products-page?limit=20&amp;sortBy=Price&amp;sortDirection=Ascending&amp;cursor=&lt;NextCursor&gt;<br>GET /api/v2/products-page?limit=20&amp;sortBy=Price&amp;sortDirection=Ascending&amp;cursor=&lt;PreviousCursor&gt;<br>GET /api/v2/products-page?limit=20&amp;pageDirection=Backward</pre><p>Empty cursor plus pageDirection=Backward is last-page navigation in the library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vGALoifbqbO9nZulRb_Iw.png" /><figcaption><em>Opaque cursors. Do not construct their contents.</em></figcaption></figure><pre>GET / POST / MVC / Dapper / MCP<br>        ↓<br>GetProductsQuery<br>        ↓<br>ISender                          BuildingBlocks.Mediator<br>        ↓<br>ProductService<br>        ↓<br>ToCursorPageAsync                BuildingBlocks.Pagination.EntityFrameworkCore<br>        ↓<br>PostgreSQL catalog</pre><p>The probe numbers in the package README are file SQLite, one machine, documented hardware. They are not here to declare a universal winner. They make the OFFSET vs keyset trade-off observable. On that probe, skip 5 million in 10 million rows was 17.8 ms keyset vs 154.9 ms OFFSET (MR 1.5.0: 19.9 ms). SQLite is not PostgreSQL. It is not SQL Server.</p><h3>What deliberately stayed in the lab</h3><p>Not everything that is useful is extracted. That is intentional.</p><p>Still inside FeatureFusion, not on nuget.org: RabbitMQ outbox and inbox, YARP plus Memcached rate limiting, Redis-backed HTTP idempotency, ASP.NET Core feature-management filters, the Dapper pagination adapter, caching middleware.</p><p>A public package hardens an API. I will not pretend every lab folder has earned that.</p><p>Pub/sub stays a sibling of Mediator, not INotification. A web/ frontend is reserved, not built.</p><h3>Prove it in the application — including Aspire</h3><p>A nice API is not a contract. The contract is what the tests refuse to let drift.</p><p>Aspire is part of the integration story, not a decorative AppHost. FeatureFusion uses it to compose the topology the application actually has, then hit real HTTP against a real PostgreSQL catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qe8stPrD0fv2SWpHKqZIZQ.png" /><figcaption><em>Each layer answers a different question. Passing CI is not a certificate that a package is production-ready everywhere.</em></figcaption></figure><p>Building-block tests pin isolated behavior. Pagination’s fast CI executes against Sqlite. One workflow, pagination-queryhint-sqlserver.yml, runs QueryHint against Aspire SQL Server (Docker; skips fail the job). That fixture is not FeatureFusion and not PostgreSQL.</p><p>FeatureFusion Aspire tests (tests/Lab/IntegrationTests) boot Postgres, Redis, RabbitMQ, and Memcached and walk GET /api/v2/products-page first, next, previous, and last page. They run in the repository. They are not a GitHub Actions workflow.</p><p>CI is path-filtered. Package jobs do not boot the lab. A few FeatureFusion.Tests use Testcontainers (for example Redis around HTTP idempotency). That is not the Aspire API fixture.</p><p>Telemetry in the lab is AddTelemetry plus local SigNoz. The screenshots below are a Development session for service FeatureFusion after catalog traffic — not an SLA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqrCSGsVM6LOJaxYmSnUtg.png" /><figcaption><em>The late spike is traffic to </em><em>GET /api/v2/products-page. Percentiles are this session only.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOAPkaHXWuWnP-_x2ApafQ.png" /><figcaption><em>mediator.send.duration is Mediator telemetry leaving the process. HTTP and Npgsql series are host instrumentation.</em></figcaption></figure><h3>Build, validate, extract, share</h3><p>Clone the <a href="https://github.com/Maxofpower/FeatureFusion">repository</a>. .NET 10 SDK and Docker for the full lab.</p><pre>dotnet run --project src/Lab/FeatureFusion.AppHost</pre><p>Open the API from the Aspire dashboard. Direct http profile: <a href="http://localhost:5141/swagger.">http://localhost:5141/swagger.</a></p><pre>GET /api/v2/products-page?limit=20&amp;sortBy=Price&amp;sortDirection=Ascending</pre><p>Take nextCursor. Send it back.</p><pre>dotnet add package BuildingBlocks.Mediator --version 1.1.0<br>dotnet add package BuildingBlocks.Pagination.EntityFrameworkCore --version 1.0.0</pre><p>dotnet test FeatureFusion.sln -c Release includes lab Aspire tests locally. That is not what every GitHub Actions workflow runs.</p><p>Inspect the implementation. Open an issue or a discussion if a boundary looks wrong. Install a package if it solves a problem you actually have. Star the repository if the lab or a BuildingBlock was useful.</p><p><a href="https://www.linkedin.com/in/mhhoseini/">https://www.linkedin.com/in/mhhoseini/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28152cafafb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[    Using  Chaining in .NET]]></title>
            <link>https://medium.com/@m2hweb86/using-chaining-in-net-a782df725b9b?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/a782df725b9b</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 11:27:22 GMT</pubDate>
            <atom:updated>2025-03-01T11:27:22.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔥 𝗖𝗵𝗮𝗶𝗻 𝗼𝗳 𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝗯𝗶𝗹𝗶𝘁𝘆 Using 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗲 Chaining in .NET</h3><p>The Chain of Responsibility or CoR pattern is 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝘂𝗻𝗱𝗲𝗿𝗲𝘀𝘁𝗶𝗺𝗮𝘁𝗲𝗱 𝘆𝗲𝘁 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹 𝗱𝗲𝘀𝗶𝗴𝗻 𝗽𝗮𝘁𝘁𝗲𝗿𝗻𝘀. It allows us to build flexible, extensible processing pipelines, just like <a href="http://asp.net/">ASP.NET</a> Core middleware or HttpClient handlers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dYT6L6xj4MOQK1mUktcYA.png" /></figure><p>𝗛𝗼𝘄 .𝗡𝗘𝗧 𝗨𝘀𝗲𝘀 𝗖𝗵𝗮𝗶𝗻 𝗼𝗳 𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝗯𝗶𝗹𝗶𝘁𝘆<br>The CoR pattern is heavily used in .NET, especially in <a href="http://asp.net/">ASP.NET</a> Core and HttpClient.</p><p>-𝗔𝗦𝗣.𝗡𝗘𝗧 𝗖𝗼𝗿𝗲 𝗠𝗶𝗱𝗱𝗹𝗲𝘄𝗮𝗿𝗲:<br>Middleware components are chained together to process HTTP requests.<br>Each middleware can decide to process the request, pass it to the next middleware, or short-circuit the pipeline.</p><p>-𝗛𝘁𝘁𝗽𝗖𝗹𝗶𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗲𝗿𝘀:<br>It uses a chain of 𝗛𝘁𝘁𝗽𝗠𝗲𝘀𝘀𝗮𝗴𝗲𝗛𝗮𝗻𝗱𝗹𝗲𝗿 instances to process HTTP requests.<br>Each handler can modify the request, pass it to the next handler, or short-circuit the pipeline.</p><p>-𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 𝗣𝗶𝗽𝗲𝗹𝗶𝗻𝗲𝘀:<br>Libraries like 𝗙𝗹𝘂𝗲𝗻𝘁𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 use a similar pattern to chain validation rules.</p><p>⚡ 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗲-𝗕𝗮𝘀𝗲𝗱 𝗖𝗼𝗥 𝗳𝗼𝗿 𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 𝗥𝘂𝗹𝗲𝘀</p><p>𝗜𝗻𝘀𝘁𝗲𝗮𝗱 𝗼𝗳 𝗵𝗮𝗿𝗱𝗰𝗼𝗱𝗶𝗻𝗴 validation logic, we 𝗱𝘆𝗻𝗮𝗺𝗶𝗰𝗮𝗹𝗹𝘆 𝗮𝗱𝗱 𝘃𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 rules using delegate chaining.</p><p>1. Define the Delegate Pipeline with Short-Circuit support.<br>2. Dynamically Add Rules<br>3. Validate Pipeline</p><p>𝗛𝗼𝘄 𝗜𝘁 𝗰𝗮𝗻 𝗛𝗲𝗹𝗽?<br>• 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 &amp; 𝗘𝘅𝘁𝗲𝗻𝘀𝗶𝗯𝗹𝗲 : Add/remove rules without modifying existing logic.<br>• 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝗢𝗽𝗲𝗻-𝗖𝗹𝗼𝘀𝗲𝗱 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗢𝗖𝗣) : New rules can be added without modifying old code.<br>• 𝗖𝗼𝗺𝗽𝗼𝘀𝗮𝗯𝗹𝗲 : Chain rules like <a href="http://asp.net/">ASP.NET</a> Core middleware.<br>• 𝗔𝘀𝘆𝗻𝗰-𝗦𝘂𝗽𝗽𝗼𝗿t : Works well with async validation.</p><p>Full 𝗶𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻 here:<br>Repo : <a href="https://lnkd.in/d5ce76Em">https://lnkd.in/d5ce76Em</a></p><p>How 𝗱𝗼 𝘆𝗼𝘂 handle validation in your system?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a782df725b9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[  and / :  Implementation vs.]]></title>
            <link>https://medium.com/@m2hweb86/and-implementation-vs-3daf5f47ee1a?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/3daf5f47ee1a</guid>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 22:58:35 GMT</pubDate>
            <atom:updated>2025-02-26T23:02:01.226Z</atom:updated>
            <content:encoded><![CDATA[<h3>𝗗𝗼𝗺𝗮𝗶𝗻 𝗘𝘃𝗲𝗻𝘁𝘀 and 𝗣𝘂𝗯/𝗦𝘂𝗯 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: 𝗠𝗮𝗻𝘂𝗮𝗹 Implementation vs. 𝗠𝗲𝗱𝗶𝗮𝘁𝗥</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*PqHFm9IAEQtUNf4Q.png" /></figure><p>𝗗𝗼𝗺𝗮𝗶𝗻 𝗲𝘃𝗲𝗻𝘁𝘀 and the 𝗽𝘂𝗯𝗹𝗶𝘀𝗵/𝘀𝘂𝗯𝘀𝗰𝗿𝗶𝗯𝗲 pattern are essential for building 𝗱𝗲𝗰𝗼𝘂𝗽𝗹𝗲𝗱, 𝘀𝗰𝗮𝗹𝗮𝗯𝗹𝗲, and 𝗺𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝗮𝗯𝗹𝗲 systems. Whether we’re working on a 𝗺𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲𝘀 architecture or a 𝗺𝗼𝗱𝘂𝗹𝗮𝗿 𝗺𝗼𝗻𝗼𝗹𝗶𝘁𝗵, these patterns help us manage complexity and enforce boundaries between 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀.<br> <br> Let’s explore two approaches to implementing domain events and pub/sub:<br> <br> • 𝗠𝗮𝗻𝘂𝗮𝗹 Implementation: A custom-built event publisher.<br> • 𝗠𝗲𝗱𝗶𝗮𝘁𝗥: A popular library for implementing the mediator pattern.<br> <br> 𝗪𝗵𝗮𝘁 𝗔𝗿𝗲 𝗗𝗼𝗺𝗮𝗶𝗻 𝗘𝘃𝗲𝗻𝘁𝘀?<br> An event is something that has happened in the past. A domain event is, something that happened in the domain that you want other parts of the same domain (in-process) to be aware of.<br> <br> 👉 𝗖𝗼𝗺𝗺𝗼𝗻 𝗨𝘀𝗲 𝗖𝗮𝘀𝗲𝘀<br> <br> 𝟭. 𝗖𝗮𝗰𝗵𝗲 𝗨𝗽𝗱𝗮𝘁𝗲𝘀<br> When an entity is updated, we may need to invalidate or update a cache.<br> <br> <br> 𝟮. 𝗙𝘂𝗹𝗹-𝗧𝗲𝘅𝘁 𝗦𝗲𝗮𝗿𝗰𝗵 𝗜𝗻𝗱𝗲𝘅𝗶𝗻𝗴 𝗨𝗽𝗱𝗮𝘁𝗲 , 𝗔𝘂𝗱𝗶𝘁𝗶𝗻𝗴 &amp; 𝗟𝗼𝗴𝗴𝗶𝗻𝗴<br> <br> When a product is updated, trigger an event to update the search index (e.g., Elasticsearch). Also we can Capture events for audit trails or log analytics.<br> <br> 𝟯. 𝗣𝘂𝗯𝗹𝗶𝘀𝗵𝗶𝗻𝗴 𝘁𝗼 𝗮 𝗠𝗲𝘀𝘀𝗮𝗴𝗲 𝗕𝗿𝗼𝗸𝗲𝗿<br> Domain events can be published to a message broker for processing by other services.<br> <br> 𝟰. 𝗘𝘃𝗲𝗻𝘁 𝗦𝗼𝘂𝗿𝗰𝗶𝗻𝗴<br> Domain events can be stored in an event store to reconstruct the state of an entity at any point in time.<br> <br> 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝟭: 𝗠𝗮𝗻𝘂𝗮𝗹 𝗜𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻<br> <br> ✅𝗣𝗿𝗼𝘀<br> 𝗙𝘂𝗹𝗹 𝗖𝗼𝗻𝘁𝗿𝗼𝗹: We have complete control over how events are published and how consumers are resolved.<br> 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲: Avoids the overhead of reflection and dynamic dispatch.<br> 𝗡𝗼 𝗘𝘅𝘁𝗲𝗿𝗻𝗮𝗹 𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝗶𝗲𝘀: Lightweight and easy to understand.<br> <br> ❌𝗖𝗼𝗻𝘀<br> 𝗕𝗼𝗶𝗹𝗲𝗿𝗽𝗹𝗮𝘁𝗲 𝗖𝗼𝗱𝗲: Requires more code to set up and maintain.<br> 𝗟𝗶𝗺𝗶𝘁𝗲𝗱 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀: No built-in support for pipelines, behaviors, or cross-cutting concerns.<br> <br> 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝟮: 𝗠𝗲𝗱𝗶𝗮𝘁𝗥<br> <br> MediatR is a popular library that simplifies the implementation of the mediator pattern, which is closely related to pub/sub.<br> <br> ✅𝗣𝗿𝗼𝘀<br> 𝗦𝗶𝗺𝗽𝗹𝗶𝗰𝗶𝘁𝘆: Easy to set up and use.<br> 𝗕𝘂𝗶𝗹𝘁-𝗜𝗻 𝗙𝗲𝗮𝘁𝘂𝗿𝗲𝘀: Supports pipelines, behaviors, and cross-cutting concerns.<br> 𝗥𝗮𝗽𝗶𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁: Great for rapid prototyping.<br> <br> ❌𝗖𝗼𝗻𝘀<br> 𝗢𝘃𝗲𝗿𝗵𝗲𝗮𝗱: Adds some overhead due to reflection and dynamic dispatch.<br> 𝗟𝗲𝘀𝘀 𝗙𝗹𝗲𝘅𝗶𝗯𝗶𝗹𝗶𝘁𝘆: Limited control over how events are published and handlers are resolved.<br> <br> Implementations:</p><p>1-Consumers (Subscribers) of Domain Events</p><pre>public partial interface IConsumer&lt;T&gt;<br>{<br>    Task HandleEventAsync(T eventMessage,CancellationToken cancellationToken = default);<br>}</pre><p>2- event Publisher Interfaces And class</p><pre>public partial interface IEventPublisher<br>{<br>    Task PublishAsync&lt;TEvent&gt;(TEvent @event,CancellationToken cancellationToken = default);<br>}<br><br>public partial class EventPublisher : IEventPublisher<br>{<br>    private readonly IServiceProvider _serviceProvider;<br> private readonly ConcurrentDictionary&lt;Type, List&lt;object&gt;&gt; _consumerCache = new();<br><br> public EventPublisher(IServiceProvider serviceProvider)<br> {<br>       _serviceProvider = serviceProvider;<br>        //to preload consumers during start up (perfomarnce optimization)<br>  PreloadConsumers();<br> }<br><br> /// &lt;returns&gt;A task that represents the asynchronous operation&lt;/returns&gt;<br> public virtual async Task PublishAsync&lt;TEvent&gt;(TEvent @event,CancellationToken cancellationToken = default)<br>    {<br>  if (_consumerCache.TryGetValue(typeof(TEvent), out var consumers))<br>  {<br>   foreach (var consumer in consumers.OfType&lt;IConsumer&lt;TEvent&gt;&gt;())<br>   {<br>    try<br>    {<br>     await consumer.HandleEventAsync(@event, cancellationToken);<br>    }<br>    catch (Exception ex)<br>    {<br>     // Handle errors<br>    }<br>   }<br>  }<br> }<br> private void PreloadConsumers()<br> {<br>  using var scope = _serviceProvider.CreateScope();<br>  var serviceProvider = scope.ServiceProvider;<br><br>  // Discover all concrete IConsumer&lt;T&gt; implementations<br>  var consumerTypes = AppDomain.CurrentDomain.GetAssemblies()<br>   .SelectMany(a =&gt; a.GetTypes())<br>   .Where(t =&gt; t.IsClass &amp;&amp; !t.IsAbstract &amp;&amp; // Ensure it&#39;s a concrete class<br>      t.GetInterfaces()<br>       .Any(i =&gt; i.IsGenericType &amp;&amp; i.GetGenericTypeDefinition() == typeof(IConsumer&lt;&gt;)))<br>   .ToList(); // Cache the results to avoid repeated enumeration<br><br>  foreach (var consumerType in consumerTypes)<br>  {<br>   // Get the event type (T) from IConsumer&lt;T&gt;<br>   var eventType = consumerType.GetInterfaces()<br>    .First(i =&gt; i.IsGenericType &amp;&amp; i.GetGenericTypeDefinition() == typeof(IConsumer&lt;&gt;))<br>    .GetGenericArguments()[0];<br><br>   // Resolve the consumer using its interface (IConsumer&lt;T&gt;)<br>   var consumerInterface = typeof(IConsumer&lt;&gt;).MakeGenericType(eventType);<br>   var consumer = serviceProvider.GetRequiredService(consumerInterface);<br><br>   // Add the consumer to the cache<br>   var consumerList = _consumerCache.GetOrAdd(eventType, _ =&gt; new List&lt;object&gt;());<br>   consumerList.Add(consumer);<br>  }<br> }</pre><p>3- Implementing MediatR (to compare benchmark with Manual one)</p><pre>public partial class ProductUpdatedEvent(Product product) : INotification<br>{<br>  // Properties based required logic<br>}<br>public class ProductUpdatedEventHandler : INotificationHandler&lt;ProductUpdatedEventMediatr&gt;<br>{<br><br> public async Task Handle(ProductUpdatedEventMediatr notification<br>  , CancellationToken cancellationToken)<br>   {<br>        //any use case (i already mentioned in the content)<br>        // Full Text search indexing update (eg ElasticSearch) , Auditing , Logging<br>        // Publishing to message broker<br>        // Storing as eventstore for event sourcing<br>        // Syncing with external services and etc<br>   }<br>}</pre><p>4- Registring in DI and Usage</p><pre>// Register Custom Publisher<br>services.AddTransient&lt;IConsumer&lt;ProductUpdatedEvent&gt;, ProductEventConsumer&gt;();<br>services.AddTransient&lt;IConsumer&lt;ProductUpdatedEvent&gt;, ProductCacheUpdateConsumer&gt;();<br>services.AddSingleton&lt;IEventPublisher, EventPublisher&gt;();<br><br>// Register MediatR<br>services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssemblyContaining&lt;Program&gt;());<br><br>//Usage<br>await _customEventPublisher.PublishAsync(new ProductUpdatedEvent(product));<br>await _mediator.Publish(new ProductUpdatedEvent(product));</pre><p>5- Benchmark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4WTtnCcQtAvQxk58.png" /></figure><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3daf5f47ee1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Consistency with   in .NET]]></title>
            <link>https://medium.com/@m2hweb86/data-consistency-with-in-net-b0f5c74541dd?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0f5c74541dd</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 09:24:28 GMT</pubDate>
            <atom:updated>2024-12-23T09:24:28.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Consistency with 𝗣𝗲𝘀𝘀𝗶𝗺𝗶𝘀𝘁𝗶𝗰 𝗟𝗼𝗰𝗸𝗶𝗻𝗴 in .NET</h3><p>🔒 Data Consistency with 𝗣𝗲𝘀𝘀𝗶𝗺𝗶𝘀𝘁𝗶𝗰 𝗟𝗼𝗰𝗸𝗶𝗻𝗴 in .NET</p><p>Pessimistic locking is an essential tool for ensuring data consistency, particularly in environments with high concurrency. It helps prevent conflicts and protects the integrity of your data by restricting access to certain rows until the transaction is complete.<br> <br>💡 𝗪𝗵𝗲𝗻 𝗦𝗵𝗼𝘂𝗹𝗱 𝗬𝗼𝘂 𝗨𝘀𝗲 𝗜𝘁?<br> <br>Use pessimistic locking when it’s critical to ensure data consistency for each transaction. For example:<br>Imagine an e-commerce platform where multiple users are placing orders for the same product. The system needs to check and update inventory levels in real-time. If two users try to purchase the last unit of the same product at the same time, without pessimistic locking, both transactions might proceed, leading to overselling the product.<br> <br>By applying UPDLOCK with NOWAIT, you ensure that once a user starts purchasing the last item, no other transaction can access and modify that product’s inventory until the first transaction is complete. If the lock cannot be acquired (e.g., someone else is already processing the order), the second transaction fails fast, preventing the issue of overselling.<br>No Partial Updates: The inventory count is updated only once per transaction, ensuring no inconsistencies.<br>No Unwanted Modifications: No other transaction can modify the inventory for that product during the order process.<br> <br>𝗧𝗵𝗶𝘀 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗶𝘀 𝗶𝗱𝗲𝗮𝗹 𝗳𝗼𝗿:<br> <br>𝗖𝗿𝗶𝘁𝗶𝗰𝗮𝗹 𝗨𝗽𝗱𝗮𝘁𝗲𝘀: Where data consistency is essential, like updating 𝗽𝗿𝗼𝗱𝘂𝗰𝘁 𝘀𝘁𝗼𝗰𝗸 𝗹𝗲𝘃𝗲𝗹𝘀 𝗱𝘂𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗰𝗵𝗲𝗰𝗸𝗼𝘂𝘁 𝗽𝗿𝗼𝗰𝗲𝘀𝘀.<br>𝗙𝗮𝗶𝗹-𝗙𝗮𝘀𝘁 𝗠𝗲𝗰𝗵𝗮𝗻𝗶𝘀𝗺𝘀: To prevent your application from hanging indefinitely when trying to acquire a lock.<br>𝗛𝗶𝗴𝗵-𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝗰𝘆 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁𝘀: Where many users might attempt to update the same data concurrently, such as in an order management system during flash sales.<br> <br>When choosing transaction isolation levels, <strong>SERIALIZABLE </strong>will lock the <strong>entire table</strong>, which may cause significant <strong>performance </strong>degradation due to broad locking behavior. On the other hand, UPDLOCK with NOWAIT allows locking only the <strong>specific rows</strong> you need, offering a <strong>more efficient approach </strong>with reduced locking overhead.<br> <br>𝗨𝘀𝗶𝗻𝗴 𝗪𝗜𝗧𝗛 (𝗨𝗣𝗗𝗟𝗢𝗖𝗞, 𝗥𝗢𝗪𝗟𝗢𝗖𝗞, 𝗡𝗢𝗪𝗔𝗜𝗧) 𝗶𝗻 𝗘𝗙 𝗖𝗼𝗿𝗲<br> <br>EF Core doesn’t natively support pessimistic locking, but you can apply it using raw SQL queries with the WITH (UPDLOCK, ROWLOCK, NOWAIT) hint For MSSQL. This allows you to lock only the rows that need to be modified, ensuring that your transaction will fail fast if the lock can’t be acquired, avoiding delays.</p><pre>    public async Task&lt;Order&gt; GetOrderWithLockAsync(Guid orderId)<br>    {<br>        return await _retryPolicy.ExecuteAsync(async () =&gt;<br>        {<br>            if (_context.IsMSSQL())<br>            {<br>                return await _context.Orders<br>                    .FromSqlRaw(<br>                        @&quot;SELECT Id,Name,Price,Qty<br>                     FROM Orders <br>                     WHERE OrderId = {0} <br>                     WITH (UPDLOCK, ROWLOCK, NOWAIT)&quot;, orderId)<br>                    .SingleOrDefaultAsync();<br>            }<br>            else if (_context.IsPostgrest())<br><br>            {<br>                return await _context.Orders<br>                    .FromSqlRaw(<br>                        @&quot;SELECT SELECT Id,Name,Price,Qty <br>                         FROM Orders <br>                         WHERE OrderId = {0} <br>                         FOR UPDATE NOWAIT&quot;, orderId)<br>                    .SingleOrDefaultAsync();<br>            }<br>        });<br>    }<br>}</pre><p><strong>Advantages</strong>:<br> <br><strong>Data Integrity</strong>: Ensures that only one transaction can modify a particular row at a time, avoiding data corruption or inconsistent states.<br><strong>Fail-Fast Behavior</strong>: With NOWAIT, if a lock can&#39;t be acquired immediately, the operation fails, preventing unnecessary delays and maintaining optimal performance.<br><strong>Conflict Prevention</strong>: Particularly useful when multiple users or systems attempt to update the same records simultaneously, preventing race conditions.<br><strong>Better Control Over Locks</strong>: You have finer control over which rows are locked, preventing unnecessary locking of unrelated records.<br><strong>Reduced Risk of Dirty Reads</strong>: Ensures that no other transaction can read or modify the data while your transaction is ongoing.</p><p><strong>Challenges &amp; Disadvantag</strong>es:<br> <br>While pessimistic locking with NOWAIT helps with fast failure, it’s not without challenges:<br>𝗦𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆 𝗖𝗼𝗻𝗰𝗲𝗿𝗻𝘀: In very high-concurrency environments, lock contention may still hinder system performance.<br><strong>Failing Fast Doesn’t Solve All Issues</strong>: Although NOWAIT prevents indefinite hangs, frequent failures to acquire locks can lead to retries, which may impact system performance.<br><strong>Complex Retry Logic</strong>: Implementing retries for failed lock attempts adds complexity, and excessive retries can increase the system’s load.<br><strong>Deadlock Risk</strong>: While pessimistic locking minimizes traditional deadlocks, complex scenarios with multiple locked resources can lead to lock starvation or indirect deadlocks.</p><p>𝗗𝗶𝘀𝗰𝗹𝗮𝗶𝗺𝗲𝗿: I’m not claiming this is the ‘best’ way, just the way I thought of it. Feel free to roast my solution and offer better ones!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0f5c74541dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ and  for a High-Volume E-Commerce System .Net]]></title>
            <link>https://medium.com/@m2hweb86/and-for-a-high-volume-e-commerce-system-net-80565ddb9fd3?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/80565ddb9fd3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 09:53:07 GMT</pubDate>
            <atom:updated>2024-12-18T09:53:07.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>𝗥𝗲𝗳𝗶𝘁 and 𝗣𝗼𝗹𝗹𝘆 for a High-Volume E-Commerce System .Net (sample: 𝗔𝗶𝗿𝗹𝗶𝗻𝗲 𝗧𝗶𝗰𝗸𝗲𝘁 𝗦𝗮𝗹𝗲𝘀)</h3><p>Recently, I’ve seen a lot of fantastic content on using Refit for clean and efficient HTTP client integrations. Today, I wanted to share how I’m 𝗱𝗶𝘃𝗶𝗻𝗴 𝗱𝗲𝗲𝗽𝗲𝗿 into more advanced ways of 𝘀𝗰𝗮𝗹𝗶𝗻𝗴 Refit usage in large systems with complex API needs.</p><p>✈️ 𝗦𝗰𝗲𝗻𝗮𝗿𝗶𝗼 : Imagine an e-commerce platform that integrates with more than 𝟭𝟬𝟬 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗮𝗶𝗿𝗹𝗶𝗻𝗲 𝗔𝗣𝗜𝘀 to sell airplane tickets. Each airline has unique routes, HTTP methods (GET, POST), and request bodies. Creating 100 separate classes for each API and route would be both cumbersome and error-prone. So, how can we handle this cleanly, adhering to SOLID principles and keeping the code maintainable?</p><p>Instead of having 𝗺𝘂𝗹𝘁𝗶𝗽𝗹𝗲 interfaces and registering Refit clients for each one in Program.cs, we can take a 𝗱𝘆𝗻𝗮𝗺𝗶𝗰 𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻-𝗱𝗿𝗶𝘃𝗲𝗻 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵. This method offers significant benefits:</p><p>✅ 𝗦𝗶𝗻𝗴𝗹𝗲 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 𝗳𝗼𝗿 𝗔𝗹𝗹 𝗔𝗣𝗜𝘀: We use a single Refit interface for all APIs and dynamically load routes and configurations. This avoids the need for creating and managing 100 different interfaces and methods.</p><p>✅ 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗔𝗣𝗜 𝗖𝗹𝗶𝗲𝗻𝘁 𝗥𝗲𝗴𝗶𝘀𝘁𝗿𝗮𝘁𝗶𝗼𝗻: Using Refit’s flexible HTTP client configuration, I’m dynamically registering the required clients for each airline directly from configuration. This avoids the need for creating separate classes for each API endpoint.</p><p>✅ 𝗣𝗼𝗹𝗹𝘆 𝗳𝗼𝗿 𝗥𝗲𝘀𝗶𝗹𝗶𝗲𝗻𝗰𝗲: I’m combining Polly for retries, circuit breakers, and resilience. Whether it’s a transient failure or a slow response, Polly ensures our system remains robust, even in the face of API downtime.</p><p>✅ 𝗦𝗢𝗟𝗜𝗗 𝗗𝗲𝘀𝗶𝗴𝗻: This approach adheres to SOLID principles.</p><p>🌟 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀</p><p>𝗗𝗥𝗬 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲: Keeps the codebase clean and avoids repetition.<br>𝗙𝗹𝗲𝘅𝗶𝗯𝗶𝗹𝗶𝘁𝘆: Easily adapts to new APIs or changes in existing ones without major code refactoring.<br>𝗥𝗲𝘀𝗶𝗹𝗶𝗲𝗻𝗰𝗲: Leveraging Polly ensures robust handling of API failures, maintaining system stability and performance.<br>𝗦𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆: As the number of APIs grows, managing separate interfaces and registrations for each becomes unwieldy. Dynamic registration simplifies this, making the system scalable.<br>𝗠𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝗮𝗯𝗶𝗹𝗶𝘁𝘆: Centralizing the configuration allows for easy updates and reduces the risk of errors. If an API changes, you update the configuration, not the code.<br>𝗘𝗳𝗳𝗶𝗰𝗶𝗲𝗻𝗰𝘆: By using a single, generic interface and dynamic configuration, we reduce code duplication and improve efficiency in managing API clients.</p><p>𝗖𝗵𝗲𝗰𝗸 <strong>My </strong>𝗥𝗲𝗽𝗼 𝗛𝗲𝗿𝗲 :<br><a href="https://github.com/Maxofpower/ApiIntegrationExample/">https://github.com/Maxofpower/ApiIntegrationExample/</a><br><strong>More Details :<br></strong><a href="https://www.linkedin.com/posts/mhhoseini_scaling-refit-and-polly-in-a-high-volume-activity-7273585021037268992-pdAI?utm_source=share&amp;utm_medium=member_desktop">https://www.linkedin.com/posts/mhhoseini_scaling-refit-and-polly-in-a-high-volume-activity-7273585021037268992-pdAI?utm_source=share&amp;utm_medium=member_desktop</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80565ddb9fd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevate Your Code with the Power of the   ]]></title>
            <link>https://medium.com/@m2hweb86/elevate-your-code-with-the-power-of-the-84a31d18267a?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a31d18267a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 14:35:19 GMT</pubDate>
            <atom:updated>2024-12-19T16:03:17.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Elevate Your Code with the Power of the 𝗚𝗲𝗻𝗲𝗿𝗶𝗰 𝗦𝗶𝗻𝗴𝗹𝗲𝘁𝗼𝗻 𝗣𝗮𝘁𝘁𝗲𝗿𝗻</p><p>we often face the challenge of managing shared resources and maintaining consistency across different parts of an application. One powerful pattern to tackle this problem is the Generic Singleton Pattern.</p><p>In my latest slides, I break down how this pattern can help us achieve efficiency, performance, and maintainability in our codebases. Here’s why you should consider using it in your projects:</p><p>🔑 Key Benefits:</p><p>𝗖𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝘆: Ensure a single instance of a class across your application, promoting a consistent state.<br>Performance: Avoid the overhead of creating multiple instances of the same class.<br>𝗙𝗹𝗲𝘅𝗶𝗯𝗶𝗹𝗶𝘁𝘆: The Generic Singleton is adaptable for different use cases (e.g., configuration settings, database connections, logging, etc.).<br>𝗧𝗵𝗿𝗲𝗮𝗱 𝗦𝗮𝗳𝗲𝘁𝘆: Easily handle thread-safe operations and prevent race conditions.</p><p>What Happens if We Manually Add Singleton in Code?</p><p>Code Duplication: Repeated patterns across the application.<br>Scalability Issues: Manually managing singletons can become cumbersome when dealing with more complex scenarios.<br>Inflexibility: Adding additional configuration or dependencies can be tricky without a flexible design.</p><p>Benefits of Using the Singleton Pattern:</p><p>Using the Generic Singleton Pattern abstracts away these challenges by providing a reusable, consistent solution. With the pattern, you:</p><p>Eliminate Code Duplication: The pattern allows you to use a single implementation across your entire application, reducing redundant code.<br>Improve Flexibility: You can manage multiple types of singletons (e.g., DatabaseConnection, ConfigurationSettings, etc.) using a generic class without adding complexity.<br>Enhance Maintainability: With a clear, unified pattern, it’s easier to manage and update how singletons are created and accessed.</p><p>📈 Real-World Use Cases:</p><p>Managing global configuration settings<br> Handling database connections<br> Implementing caching mechanisms<br> Centralizing logging functionality</p><p>Check It out , I walk through the problems with traditional singleton implementations, demonstrate how to implement a generic singleton, and provide best practices to ensure safe and efficient use.</p><pre>  public class BaseSingleton<br>  {<br>      static BaseSingleton()<br>      {<br>          AllSingletons = new ConcurrentDictionary&lt;Type, object&gt;();<br>      }<br><br>      /// &lt;summary&gt;<br>      /// Dictionary of type to singleton instances.<br>      /// &lt;/summary&gt;<br>      public static ConcurrentDictionary&lt;Type, object&gt; AllSingletons { get; }<br>  }<br><br> public class Singleton&lt;T&gt; : BaseSingleton<br> {<br>     private static T instance;<br><br>     /// &lt;summary&gt;<br>     /// The singleton instance for the specified type T. Only one instance (at the time) of this object for each type of T.<br>     /// &lt;/summary&gt;<br>     public static T Instance<br>     {<br>         get =&gt; instance;<br>         set<br>         {<br>             instance = value;<br>             AllSingletons[typeof(T)] = value;<br>         }<br>     }<br> }</pre><p><strong>Thread Safety</strong>: When working in multi-threaded environments, make sure to implement thread-safe mechanisms (e.g., Lazy Initialization or lock statements) to avoid issues with race conditions and ensure that the singleton instance is accessed safely across multiple threads.</p><p><strong>Lazy Initialization</strong>:Delay the instantiation of the singleton until it is actually needed, reducing the initial overhead and improving performance. Use Lazy&lt;T&gt; for automatic lazy initialization.</p><p><strong>Dispose Singleton Instances When Necessary</strong>:<br>If your singleton manages resources like database connections, files, or network connections, make sure to implement a Dispose method to clean up resources when they are no longer needed.</p><p>a basic example how we can use this singleton :</p><pre>    public partial class CacheKey<br>    {<br><br>        #region Properties<br><br>        /// &lt;summary&gt;<br>        /// Gets or sets a cache key<br>        /// &lt;/summary&gt;<br>        public string Key { get; protected set; }<br><br>        /// &lt;summary&gt;<br>        /// Gets or sets prefixes for remove by prefix functionality<br>        /// &lt;/summary&gt;<br>        public List&lt;string&gt; Prefixes { get; protected set; } = new List&lt;string&gt;();<br><br>        /// &lt;summary&gt;<br>        /// Gets or sets a cache time in minutes<br>        /// &lt;/summary&gt;<br>        public int CacheTime { get; set; } = Singleton&lt;AppSettings&gt;.Instance.CacheConfig.DefaultCacheTime;<br><br>     }</pre><p><strong>Conclusion and Takeaways :<br></strong>Generic Singleton pattern is an essential design pattern that provides a single, consistent instance of a class across your entire application, ensuring efficient memory usage and easy management of shared resources.</p><p><strong>Flexibility</strong>: The pattern is generic, meaning it can be used for any type (e.g., configuration, caching, etc.), reducing the need for boilerplate code.</p><p><strong>Efficiency</strong>: By using a singleton, you eliminate the overhead of creating and managing multiple instances of the same class, which can lead to significant performance improvements</p><p><strong>Maintainability</strong>: Centralizing access to resources through a singleton improves the maintainability of your codebase, making it easier to manage configuration settings, caching mechanisms, or other shared components.</p><p><strong>Key Use Cases</strong>: Singleton is perfect for managing configuration settings, database connections, caching, logging, and other globally shared resources in a clean and efficient way.</p><p>💬 What are your thoughts on the Generic Singleton Pattern? Have you used it in your projects? How did it help improve your code?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a31d18267a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionize Your Async Workflows with . in .NET 9]]></title>
            <link>https://medium.com/@m2hweb86/revolutionize-your-async-workflows-with-in-net-9-d2520eaa79b2?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2520eaa79b2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 17:38:10 GMT</pubDate>
            <atom:updated>2024-12-14T17:38:10.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionize Your Async Workflows with 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗘𝗮𝗰𝗵 in .NET 9</h3><p>As developers, we often encounter scenarios where we need to run multiple asynchronous tasks in parallel. Traditionally, we’ve used 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗔𝗹𝗹 or 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗔𝗻𝘆 to handle these situations. However, with .NET 9, a powerful new feature called 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗘𝗮𝗰𝗵 has been introduced, allowing us to process tasks as they complete.</p><p>🌐 Practical Scenario: Real-Time Data Processing in a Distributed System</p><p>Imagine you’re building a real-time monitoring system for a fleet of IoT devices. Each device sends telemetry data periodically, and your backend needs to process this data as soon as it arrives to detect anomalies and trigger alerts. The telemetry data from each device is processed asynchronously, and it’s crucial to handle the results as they come in to ensure timely responses.</p><p>🕰️ Traditional Approach with 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗔𝗹𝗹</p><p>Using Task.WhenAll, you would typically wait for all telemetry data processing tasks to complete before handling the results. This can introduce unnecessary latency, as you can only act once the last task is finished.</p><p>⚡ Modern Approach with 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗘𝗮𝗰𝗵</p><p>With Task.WhenEach, you can process each task’s result as soon as it completes, significantly reducing 𝗹𝗮𝘁𝗲𝗻𝗰𝘆 and improving the 𝗿𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝘃𝗲𝗻𝗲𝘀𝘀 of your system.</p><p>🧠 𝗛𝗼𝘄 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗘𝗮𝗰𝗵 𝗪𝗼𝗿𝗸𝘀 𝗨𝗻𝗱𝗲𝗿 𝘁𝗵𝗲 𝗛𝗼𝗼𝗱</p><p>Since 𝗧𝗮𝘀𝗸.𝗪𝗵𝗲𝗻𝗘𝗮𝗰𝗵 returns an 𝗜𝗔𝘀𝘆𝗻𝗰𝗘𝗻𝘂𝗺𝗲𝗿𝗮𝗯𝗹𝗲&lt;𝗧𝗮𝘀𝗸&gt;, you can use 𝗮𝘄𝗮𝗶𝘁 𝗳𝗼𝗿𝗲𝗮𝗰𝗵. This loop will iterate over all the completed tasks as they finish.</p><p>𝟭. 𝗧𝗮𝘀𝗸 𝗦𝗰𝗵𝗲𝗱𝘂𝗹𝗶𝗻𝗴: Tasks are scheduled on the thread pool, which manages a pool of worker threads to execute tasks asynchronously. The thread pool dynamically adjusts the number of threads to handle varying workloads efficiently.</p><p>𝟮. 𝗧𝗮𝘀𝗸 𝗖𝗼𝗺𝗽𝗹𝗲𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: As each task completes, its result or exception is immediately available for processing. This allows you to handle results as soon as they’re ready, without waiting for other tasks to finish.</p><p>3. 𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝗰𝘆 𝗖𝗼𝗻𝘁𝗿𝗼𝗹: The thread pool ensures that tasks are executed concurrently but within the limits of available system resources. It prevents overloading the system by managing the number of active threads.</p><p>𝟰. 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: Task.WhenEach provides fine-grained control over error handling. You can handle exceptions on a per-task basis, allowing your application to continue processing other tasks even if one fails.</p><p>🏁 𝗖𝗼𝗻𝗰𝗹𝘂𝘀𝗶𝗼𝗻</p><p>Task.WhenEach in .NET 9 is a powerful tool for handling multiple asynchronous tasks in a more efficient and responsive manner. By processing tasks as they complete, you can significantly improve the performance of real-time systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*NOGuvVRbrYp7x5RMM0dPxg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2520eaa79b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Performance with Span<T> in .Net]]></title>
            <link>https://medium.com/@m2hweb86/unlocking-performance-with-span-t-in-net-bb17a75c23be?source=rss-e28028b31f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb17a75c23be</guid>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mohammad Hasan Hosseini]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 15:13:44 GMT</pubDate>
            <atom:updated>2024-12-06T15:13:44.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Performance with Span&lt;T&gt; in .Net</h3><p>As developers, we’re always on the lookout for ways to optimize our code and boost performance. One powerful tool in the .NET ecosystem that often goes underutilized is Span&lt;T&gt;. Let’s dive into what it is, when to use it, and why it’s beneficial, referencing Microsoft’s guidelines and insights from Silent Exception.</p><p>🔍<strong> What is Span&lt;T&gt;?</strong><br>Span&lt;T&gt; is a stack-only type that provides a type-safe and memory-safe representation of contiguous memory. It allows you to work with slices of arrays, strings, and unmanaged memory without any heap allocation, making it a powerful tool for performance-critical applications. Essentially, Span&lt;T&gt; is a value type for representing contiguous arbitrary memory. It’s a facade over arrays, strings, and any contiguous memory with almost no overhead. The main purpose of Span&lt;T&gt; is writing low-allocation code, which leads to cutting down managed memory allocations and reduces the load on the Garbage Collector (GC).</p><p>⚡<strong> Why Use Span&lt;T&gt;?</strong><br>Performance Gains: By avoiding heap allocations, Span&lt;T&gt; reduces garbage collection pressure, leading to faster and more predictable performance.</p><p><strong>Memory Safety</strong>: Span&lt;T&gt; ensures type and memory safety, preventing common bugs like buffer overruns.</p><p><strong>Simplified Code</strong>: It provides a unified way to work with different types of memory, simplifying code and reducing the need for unsafe code.</p><p><strong>Versatility</strong>: Span&lt;T&gt; can wrap managed memory (handled by GC), unmanaged memory (invisible to GC), and stack-allocated memory, allowing safe access to all these types.</p><p><strong>📈 Benefits of Using Span&lt;T&gt; for Sorting and Grouping</strong><br>By creating a Span&lt;T&gt; from collections, you can sort the data in place without allocating additional memory. This means that operations like Sort() become more efficient, reducing the load on the garbage collector and improving overall application performance.</p><p><strong>🛠️ When to Use Span&lt;T&gt;?</strong><br>According to Microsoft’s guidelines, here are some scenarios where Span&lt;T&gt; shines:</p><p><strong>String Manipulations</strong>: When working with substrings or slicing strings without allocating new strings, Span&lt;char&gt; is invaluable.</p><p><strong>Array Slicing</strong>: If you need to work with a portion of an array without creating a copy, Span&lt;T&gt; is perfect.</p><p><strong>Interoperability with Unmanaged Code</strong>: Span&lt;T&gt; can represent unmanaged memory buffers, making it useful in P/Invoke scenarios or when working with low-level APIs.</p><p><strong>Performance-Critical Code</strong>: Anytime you have a hot path in your application where performance is key, consider using Span&lt;T&gt; to minimize allocations and improve efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kGo-W3zy50moTduf055sPg.jpeg" /><figcaption>Span&lt;T&gt; vs Substring Benchmark</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb17a75c23be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>