<?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 Satyam Pushkar on Medium]]></title>
        <description><![CDATA[Stories by Satyam Pushkar on Medium]]></description>
        <link>https://medium.com/@satyampushkar?source=rss-1a12c14f5892------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LDUcW7TDC9KEiP0ycO-FOA.jpeg</url>
            <title>Stories by Satyam Pushkar on Medium</title>
            <link>https://medium.com/@satyampushkar?source=rss-1a12c14f5892------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:35:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyampushkar/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[Beyond Convention-Based Middleware: Mastering Factory-Based IMiddleware in ASP.NET Core]]></title>
            <link>https://satyampushkar.medium.com/beyond-convention-based-middleware-mastering-factory-based-imiddleware-in-asp-net-core-8bdc2140cc51?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdc2140cc51</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 17:40:07 GMT</pubDate>
            <atom:updated>2026-10-21T17:40:07.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ciMI8-LCBob5qTmomneTA.png" /></figure><p>In ASP.NET Core, middleware forms the core processing pipeline for every incoming HTTP request. Whether you are handling authentication, logging, global exception handling, or custom tenant resolution, middleware is where cross-cutting concerns live.</p><p>Most tutorials teach the standard <strong>convention-based</strong> middleware pattern — creating a class with a RequestDelegate in its constructor and an InvokeAsync(HttpContext context) method. However, when middleware needs scoped dependencies, you have two options: inject them into InvokeAsync parameters in convention-based middleware, or use factory-based middleware to support constructor injection.</p><p>In this article, we’ll explore why convention-based middleware can lead to subtle architecture bugs like captive dependencies, and how transitioning to <strong>Factory-Based Middleware (</strong><strong>IMiddleware)</strong> gives you strong typing, per-request activation, and clean constructor injection.</p><h3>Problem Statement: The Scoped Dependency Trap in Convention Middleware</h3><p>Imagine you need to create a custom middleware called TenantLoggingMiddleware that extracts a tenant ID from request headers, validates it against a scoped database service (ITenantService), and logs the request details.</p><p>Following the typical convention-based approach, developers often write something like this:</p><pre>// BAD: Injecting a Scoped service into a Convention-based Middleware Constructor<br>public class TenantLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly ITenantService _tenantService; // Scoped dependency!<br>    // Convention constructor requiring RequestDelegate<br>    public TenantLoggingMiddleware(RequestDelegate next, ITenantService tenantService)<br>    {<br>        _next = next;<br>        _tenantService = tenantService; // CAPTIVE DEPENDENCY BUG!<br>    }<br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var tenant = await _tenantService.GetTenantAsync(context);<br>        // Process request...<br>        await _next(context);<br>    }<br>}</pre><h3>Why is this dangerous?</h3><p>Convention-based middleware is constructed when the application pipeline is built and is reused across requests. As a result, injecting a scoped service such as ITenantService into its constructor is invalid because the service would be captured for the middleware&#39;s application lifetime rather than resolved from each request&#39;s scope.</p><p>Depending on the configuration, scope validation can detect this lifetime mismatch. If it goes undetected, the middleware may retain scoped state longer than intended and share it across concurrent requests, potentially causing incorrect behavior and thread-safety issues.</p><p>To use scoped dependencies in convention-based middleware, inject them into the InvokeAsync method parameters. ASP.NET Core resolves these parameters from the current request&#39;s service scope, so the middleware can use scoped services without capturing them in its constructor:</p><pre>// Clunky workaround in convention middleware: Method Injection<br>public async Task InvokeAsync(HttpContext context, ITenantService tenantService)<br>{<br>    // Method injection works, but strays from standard constructor injection patterns<br>}</pre><p>To use scoped dependencies in convention-based middleware, inject them into the InvokeAsync method parameters. ASP.NET Core resolves these parameters from the current request&#39;s service scope, so the middleware can use scoped services without capturing them in its constructor.</p><p>This approach is perfectly valid. However, if you prefer constructor injection for middleware dependencies, factory-based middleware provides a natural alternative.</p><p>And that’s where factory-based middleware comes in.</p><h3>The Solution: Factory-Based Middleware (IMiddleware)</h3><p>ASP.NET Core provides a strongly-typed alternative called <strong>Factory-Based Middleware</strong> by implementing the IMiddleware interface.</p><p>Unlike convention-based middleware, factory-based middleware is activated through IMiddlewareFactory for each HTTP request that reaches it. Registering the middleware as Scoped gives it one instance per request scope, allowing scoped dependencies to be injected directly into its constructor.</p><h3>Key Advantages of IMiddleware:</h3><ol><li><strong>Strong Typing:</strong> Inheriting from IMiddleware enforces the exact InvokeAsync(HttpContext context, RequestDelegate next) signature at compile time.</li><li><strong>Standard Constructor Injection:</strong> Supports constructor injection of scoped, transient, and singleton dependencies. When the middleware is registered with an appropriate lifetime, typically Scoped, scoped dependencies can be resolved from the current request’s scope without being captured for the application’s lifetime.</li><li><strong>Per-Request Activation:</strong> Factory-based middleware is activated through DI for each request. Registering it as Scoped provides one instance per request scope, allowing it to use scoped dependencies safely without sharing the middleware instance across requests.</li></ol><h3>Implementation: Building a Factory-Based Middleware</h3><p>Let’s refactor our TenantLoggingMiddleware to use the factory-based approach.</p><h3>Step 1: Implement the IMiddleware Interface</h3><p>Create your class and implement IMiddleware. Notice how both HttpContext and RequestDelegate next are passed directly into InvokeAsync:</p><pre>using Microsoft.AspNetCore.Http;<br><br>public class TenantLoggingMiddleware : IMiddleware<br>{<br>    private readonly ITenantService _tenantService;<br>    private readonly ILogger&lt;TenantLoggingMiddleware&gt; _logger;<br>    // GOOD: Scoped dependencies can be safely injected into the constructor!<br>    public TenantLoggingMiddleware(<br>        ITenantService tenantService,<br>        ILogger&lt;TenantLoggingMiddleware&gt; logger)<br>    {<br>        _tenantService = tenantService;<br>        _logger = logger;<br>    }<br>    public async Task InvokeAsync(HttpContext context, RequestDelegate next)<br>    {<br>        var tenant = await _tenantService.GetTenantAsync(context);<br>        _logger.LogInformation(&quot;Processing request for Tenant: {TenantId}&quot;, tenant?.Id);<br>        // Call the next delegate in the pipeline<br>        await next(context);<br>    }<br>}</pre><h3>Step 2: Register in DI &amp; Configure the Pipeline</h3><p>Because factory-based middleware is resolved from the DI container via IMiddlewareFactory, <strong>you must register the middleware class in </strong><strong>IServiceCollection</strong> in Program.cs.</p><pre>var builder = WebApplication.CreateBuilder(args);<br>// 1. Register scoped services<br>builder.Services.AddScoped&lt;ITenantService, TenantService&gt;();<br>// 2. MUST register factory-based middleware in DI (usually as Scoped)<br>builder.Services.AddScoped&lt;TenantLoggingMiddleware&gt;();<br>var app = builder.Build();<br>// 3. Add middleware to the HTTP processing pipeline<br>app.UseMiddleware&lt;TenantLoggingMiddleware&gt;();<br>app.Run();</pre><blockquote><strong><em>Important Note:</em></strong><em> If you forget to register your factory-based middleware in </em><em>IServiceCollection, ASP.NET Core will throw an </em><em>InvalidOperationException at runtime when a request hits the pipeline because </em><em>IMiddlewareFactory won&#39;t be able to resolve it.</em></blockquote><h3>Convention vs. Factory-Based Middleware: Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8a0rXp1OGnVAt4S3Z5wbug.png" /></figure><h3>Summary</h3><p>Choosing between convention-based and factory-based middleware depends on how your middleware needs to consume dependencies.</p><ul><li><strong>Convention-based middleware:</strong> A good fit for lightweight pipeline logic. Inject scoped services through InvokeAsync parameters when needed.</li><li><strong>Factory-based middleware (</strong><strong>IMiddleware):</strong> A good fit when you prefer standard constructor injection for scoped dependencies or want middleware activation managed by DI.</li></ul><p>Both approaches are valid. Choose the one that keeps dependency lifetimes correct and makes your middleware easiest to understand and maintain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdc2140cc51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Clean Ways to Dynamically Resolve Dependencies at Runtime in .NET]]></title>
            <link>https://satyampushkar.medium.com/3-clean-ways-to-dynamically-resolve-dependencies-at-runtime-in-net-db21e76008b5?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/db21e76008b5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 17:21:40 GMT</pubDate>
            <atom:updated>2026-10-12T17:21:40.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ySPJrUlYQe9_cOVlNJ80w.png" /></figure><p>When building extensible applications, you often encounter situations where multiple concrete classes implement the exact same interface.</p><p>Consider a food delivery or e-commerce platform where users can pay via Stripe, PayPal, or Razorpay. All three implement a common IPaymentProcessor interface. At runtime, when an incoming request specifies &quot;paymentMethod&quot;: &quot;Stripe&quot;, how does your application pick the right service instance cleanly without resorting to messy switch statements or hardcoded conditional logic?</p><p>In this article, we’ll explore 3 modern, clean patterns to dynamically resolve dependencies at runtime in .NET.</p><p><strong>The Anti-Pattern: Service Locator with Conditional Resolution</strong></p><p>Developers often handle dynamic resolution by passing IServiceProvider directly into a controller or service and using a switch statement:</p><pre>// ❌ BAD: Messy switch block + Service Locator Anti-Pattern<br>public class PaymentService<br>{<br>    private readonly IServiceProvider _serviceProvider;<br><br>    public PaymentService(IServiceProvider serviceProvider)<br>    {<br>        _serviceProvider = serviceProvider;<br>    }<br>    public async Task ProcessPayment(string method, decimal amount)<br>    {<br>        // Pulling dependencies manually at runtime via switch<br>        IPaymentProcessor processor = method.ToLowerInvariant() switch<br>        {<br>            &quot;stripe&quot; =&gt; _serviceProvider.GetRequiredService&lt;StripeProcessor&gt;(),<br>            &quot;paypal&quot; =&gt; _serviceProvider.GetRequiredService&lt;PaypalProcessor&gt;(),<br>            &quot;razorpay&quot; =&gt; _serviceProvider.GetRequiredService&lt;RazorpayProcessor&gt;(),<br>            _ =&gt; throw new NotSupportedException(&quot;Payment method not supported&quot;)<br>        };<br>        await processor.ProcessAsync(amount);<br>    }<br>}</pre><p>Using IServiceProvider to manually resolve dependencies at runtime hides a class&#39;s actual dependencies, makes unit testing harder, and couples application logic directly to the DI container.</p><p><em>And that, my friend, is an anti-pattern in software design.</em></p><p><strong>Pattern 1: Native Keyed Services</strong></p><p>Modern .NET includes native support for Keyed Services. This feature allows you to register multiple implementations of the same interface using a unique key (such as a string, enum, or type).</p><p><strong>1. Registering Keyed Services</strong></p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Registering multiple implementations using keys<br>builder.Services.AddKeyedScoped&lt;IPaymentProcessor, StripeProcessor&gt;(&quot;stripe&quot;);<br>builder.Services.AddKeyedScoped&lt;IPaymentProcessor, PaypalProcessor&gt;(&quot;paypal&quot;);<br>builder.Services.AddKeyedScoped&lt;IPaymentProcessor, RazorpayProcessor&gt;(&quot;razorpay&quot;);</pre><p><strong>2. Resolving at Runtime</strong></p><p>If you know the required implementation key at compile time, you can inject it directly using the [FromKeyedServices] attribute:</p><pre>public class OrderCheckoutHandler<br>{<br>    private readonly IPaymentProcessor _stripeProcessor;<br><br>    // Direct injection via key attribute<br>    public OrderCheckoutHandler([FromKeyedServices(&quot;stripe&quot;)] IPaymentProcessor stripeProcessor)<br>    {<br>        _stripeProcessor = stripeProcessor;<br>    }<br>}</pre><p>If the payment method key is dynamic (supplied in an HTTP request payload), resolve it cleanly via IKeyedServiceProvider:</p><pre>public class PaymentService<br>{<br>    private readonly IKeyedServiceProvider _keyedProvider;<br><br>    public PaymentService(IKeyedServiceProvider keyedProvider)<br>    {<br>        _keyedProvider = keyedProvider;<br>    }<br>    public async Task ProcessPaymentAsync(string methodKey, decimal amount)<br>    {<br>        // Dynamically resolve the exact instance matching the key<br>        var processor = _keyedProvider.GetKeyedService&lt;IPaymentProcessor&gt;(methodKey.ToLowerInvariant())<br>            ?? throw new NotSupportedException($&quot;Processor &#39;{methodKey}&#39; is not registered.&quot;);<br>        await processor.ProcessAsync(amount);<br>    }<br>}</pre><p><strong>Pattern 2: The </strong>IEnumerable&lt;T&gt;<strong> Strategy Pattern</strong></p><p>If you prefer not to rely on string keys during DI registration, you can use the Strategy Pattern by injecting all registered implementations as an IEnumerable&lt;T&gt; collection.</p><p><strong>1. Update the Interface Contract</strong></p><p>Add a CanHandle predicate method to your interface contract so each concrete class identifies which requests it supports:</p><pre>public interface IPaymentProcessor<br>{<br>    bool CanHandle(string paymentMethod);<br>    Task ProcessAsync(decimal amount);<br>}<br><br>public class StripeProcessor : IPaymentProcessor<br>{<br>    public bool CanHandle(string paymentMethod) =&gt; paymentMethod.Equals(&quot;stripe&quot;, StringComparison.OrdinalIgnoreCase);<br>    public Task ProcessAsync(decimal amount) =&gt; /* Stripe API execution */ Task.CompletedTask;<br>}</pre><p><strong>2. Register Services Standardly</strong></p><pre>builder.Services.AddScoped&lt;IPaymentProcessor, StripeProcessor&gt;();<br>builder.Services.AddScoped&lt;IPaymentProcessor, PaypalProcessor&gt;();</pre><p><strong>3. Resolve via Strategy Selection</strong></p><p>Inject IEnumerable&lt;IPaymentProcessor&gt; into your service. The DI container resolves all registered implementations and supplies them as an IEnumerable&lt;IPaymentProcessor&gt;. You can then select the appropriate strategy using each implementation&#39;s CanHandle() method.</p><pre>public class PaymentService<br>{<br>    private readonly IEnumerable&lt;IPaymentProcessor&gt; _processors;<br><br>    // DI automatically passes ALL registered IPaymentProcessor instances<br>    public PaymentService(IEnumerable&lt;IPaymentProcessor&gt; processors)<br>    {<br>        _processors = processors;<br>    }<br>    public async Task ProcessPaymentAsync(string method, decimal amount)<br>    {<br>        var processor = _processors.FirstOrDefault(p =&gt; p.CanHandle(method))<br>            ?? throw new NotSupportedException($&quot;No processor found for {method}&quot;);<br>        await processor.ProcessAsync(amount);<br>    }<br>}</pre><p><strong>Pattern 3: Factory Delegate for Custom Runtime Resolution (</strong>Func&lt;string, IPaymentProcessor&gt;<strong>)</strong></p><p>When service selection requires custom mapping or instantiation logic based on runtime arguments, a factory delegate can centralize that logic in the DI registration. The consuming service depends on a simple Func&lt;string, IPaymentProcessor&gt; rather than directly resolving concrete implementations through IServiceProvider.</p><p>This keeps service-location logic out of the application service, although the factory delegate itself still uses IServiceProvider to resolve the required implementation.</p><pre>// Register concrete classes<br>builder.Services.AddScoped&lt;StripeProcessor&gt;();<br>builder.Services.AddScoped&lt;PaypalProcessor&gt;();<br><br>// Register a delegate resolver<br>builder.Services.AddScoped&lt;Func&lt;string, IPaymentProcessor&gt;&gt;(serviceProvider =&gt; key =&gt;<br>{<br>    return key.ToLowerInvariant() switch<br>    {<br>        &quot;stripe&quot; =&gt; serviceProvider.GetRequiredService&lt;StripeProcessor&gt;(),<br>        &quot;paypal&quot; =&gt; serviceProvider.GetRequiredService&lt;PaypalProcessor&gt;(),<br>        _ =&gt; throw new KeyNotFoundException($&quot;Key {key} not registered&quot;)<br>    };<br>});</pre><p>Now, your application service simply requests Func&lt;string, IPaymentProcessor&gt; in its constructor:</p><pre>public class PaymentService<br>{<br>    private readonly Func&lt;string, IPaymentProcessor&gt; _processorFactory;<br><br>public PaymentService(Func&lt;string, IPaymentProcessor&gt; processorFactory)<br>    {<br>        _processorFactory = processorFactory;<br>    }<br>    public async Task ProcessPaymentAsync(string method, decimal amount)<br>    {<br>        var processor = _processorFactory(method);<br>        await processor.ProcessAsync(amount);<br>    }<br>}</pre><h4>Choosing the Right Pattern</h4><p>A quick comparison of the three runtime resolution approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7H3YnWUsI3IA2jjqQETiA.png" /></figure><p>There is no single best approach for every scenario.</p><ul><li><strong>Keyed Services:</strong> Use when explicit keys are sufficient to select an implementation.</li><li><strong>Strategy Pattern (</strong><strong>IEnumerable&lt;T&gt;):</strong> Use when implementations should determine which requests they can handle.</li><li><strong>Factory Delegate:</strong> Use when custom runtime selection logic is justified.</li></ul><p>Keep the selection mechanism as simple as the problem allows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db21e76008b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Built-in .NET DI vs. Autofac: When Do You Actually Need a Third-Party Container]]></title>
            <link>https://satyampushkar.medium.com/built-in-net-di-vs-autofac-when-do-you-actually-need-a-third-party-container-2a66ce4cd260?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a66ce4cd260</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 16:46:01 GMT</pubDate>
            <atom:updated>2026-10-07T16:46:01.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kiMCTMy73H-pARnP7RAGg.png" /></figure><p>ASP.NET Core and modern .NET applications include a built-in Dependency Injection (DI) container, Microsoft.Extensions.DependencyInjection. It supports constructor injection, resolves dependency graphs, and manages Transient, Scoped, and Singleton lifetimes.</p><p>Microsoft describes the built-in container as a ‘conforming container’: it provides the core DI capabilities required by the .NET framework and most applications, while allowing applications with specialized requirements to replace it with a third-party container.</p><p>So why do senior developers and enterprise teams still plug in third-party containers like Autofac? Is it just legacy habit, or are there real architectural features that the built-in container cannot handle?</p><p>In this article, we’ll compare the built-in .NET DI container with Autofac and examine the specific scenarios where a third-party container can be justified. The goal isn’t to determine which container is ‘better.’ <em>For most modern .NET applications, the built-in container is the better default</em>. The interesting question is <em>what specific requirements justify adding the complexity of another container</em>.</p><p><strong>1. Aspect-Oriented Programming (AOP) &amp; Method Interception</strong></p><p><strong>The Built-in Container Limitation</strong></p><p>For cross-cutting concerns such as performance logging, execution timing, or audit logging, the built-in container doesn’t provide dynamic method interception. Depending on the scenario, you can use middleware, filters, decorators, or other patterns — but these generally require explicit wiring.</p><p><strong>The Autofac Advantage: Interception</strong></p><p>Autofac supports AOP interception, providing another option through runtime-generated proxies. A single interceptor can apply cross-cutting behavior to multiple services without modifying the business code or writing individual decorators for every service.</p><pre>// 1. Define a generic Interceptor<br>public class CallLoggingInterceptor : IInterceptor<br>{<br>    public void Intercept(IInvocation invocation)<br>    {<br>        Console.WriteLine($&quot;Calling method: {invocation.Method.Name}&quot;);<br>        invocation.Proceed(); // Execute the actual service method<br>        Console.WriteLine($&quot;Completed method: {invocation.Method.Name}&quot;);<br>    }<br>}<br><br>// 2. Register with Autofac and enable interception across all services<br>builder.Host.ConfigureContainer&lt;ContainerBuilder&gt;(autofacBuilder =&gt;<br>{<br>    autofacBuilder.RegisterType&lt;CallLoggingInterceptor&gt;();<br>    autofacBuilder.RegisterType&lt;OrderService&gt;()<br>        .As&lt;IOrderService&gt;()<br>        .EnableInterfaceInterceptors()<br>        .InterceptedBy(typeof(CallLoggingInterceptor)); // Intercepts calls through the registered interface<br>});</pre><p><strong>Note:</strong> Autofac interception is proxy-based, so interception depends on how the service is registered and consumed. Interface interception is different from class interception, and not every method invocation is automatically interceptable.</p><p><strong>2. Automatic Property Injection</strong></p><p><strong>The Built-in Container Limitation</strong></p><p>The built-in container focuses on constructor injection. This is generally the preferred approach for required dependencies because it makes dependencies explicit and allows objects to be created in a valid state. However, some legacy codebases or framework-integrated components are easier to work with when optional dependencies can be injected through properties.</p><p><strong>The Autofac Advantage</strong></p><p>Autofac supports property injection, allowing dependencies to be populated through public settable properties when an object is created. This can be useful for genuinely optional dependencies, legacy codebases, or framework-integrated components where constructors are managed externally.</p><pre>public interface IReportFormatter<br>{<br>    void Format(string report);<br>}<br><br>public class ReportGenerator<br>{<br>    // Optional dependency — Autofac can inject this property automatically<br>    public IReportFormatter? Formatter { get; set; }<br><br>    public void Generate()<br>    {<br>        if (Formatter != null)<br>        {<br>            Formatter.Format(&quot;Generating report...&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;Generating report with default formatting...&quot;);<br>        }<br>    }<br>}<br><br>// Autofac Registration:<br>autofacBuilder.RegisterType&lt;ReportFormatter&gt;()<br>    .As&lt;IReportFormatter&gt;();<br><br>autofacBuilder.RegisterType&lt;ReportGenerator&gt;()<br>    .PropertiesAutowired();</pre><p><strong>Note:</strong> Constructor injection should generally remain the preferred approach for required dependencies. Property injection is most useful when a dependency is genuinely optional or when the object’s construction cannot be easily controlled.</p><p><strong>3. Modular Architecture with </strong>Autofac.Module</p><p><strong>The Built-in Container Limitation</strong></p><p>The built-in container doesn’t provide a first-class module abstraction like Autofac’s Module class. You can achieve similar organization using registration extension methods, but Autofac provides a dedicated module abstraction for structuring container configuration.</p><p><strong>The Autofac Advantage: </strong>Module<strong> Classes</strong></p><p>Autofac provides a dedicated Module class. Each project, layer, or class library in your solution can define its own self-contained module:</p><pre>public class OrderingModule : Autofac.Module<br>{<br>    protected override void Load(ContainerBuilder builder)<br>    {<br>        // Encapsulated registrations for the Ordering domain<br>        builder.RegisterType&lt;OrderRepository&gt;().As&lt;IOrderRepository&gt;().InstancePerLifetimeScope();<br>        builder.RegisterType&lt;OrderService&gt;().As&lt;IOrderService&gt;().InstancePerLifetimeScope();<br>    }<br>}<br><br>// In Program.cs, simply register the module:<br>builder.Host.ConfigureContainer&lt;ContainerBuilder&gt;(autofacBuilder =&gt;<br>{<br>    autofacBuilder.RegisterModule&lt;OrderingModule&gt;();<br>});</pre><p>This keeps domain modules encapsulated and cleanly organized across large engineering teams.</p><p><strong>4. Advanced Lifetime Scopes &amp; Tagging</strong></p><p><strong>The Built-in Container Limitation</strong></p><p>The built-in container supports three standard service lifetimes: Transient, Scoped, and Singleton. A Scoped service is created once within a particular scope; in ASP.NET Core, a scope is typically created for each HTTP request. Scopes can also be created explicitly in background services and messaging applications using IServiceScopeFactory.</p><p>This is sufficient for many background-processing and messaging scenarios. However, when an application needs richer lifetime semantics — for example, associating certain components with a specific type of processing scope — the built-in container provides fewer built-in mechanisms for expressing those relationships declaratively.</p><p><strong>The Autofac Advantage</strong></p><p>Autofac provides more granular lifetime-scope management, including named or tagged scopes such as InstancePerMatchingLifetimeScope(&quot;messageBatch&quot;) and ownership-based lifetimes such as InstancePerOwned&lt;T&gt;. This allows registrations to express more specific relationships between services and lifetime scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*5xpsNGpUQcPLqlmU8cEeRg.png" /></figure><p><strong>5. Advanced Registration &amp; Convention-Based Configuration</strong></p><p><strong>The Built-in Container Limitation</strong></p><p>The built-in container provides explicit registration APIs and can be organized using extension methods, but it offers fewer built-in mechanisms for convention-based registration than containers such as Autofac.</p><p><strong>The Autofac Advantage</strong></p><p>Autofac supports more advanced registration patterns, including assembly scanning, conditional registration, metadata, and other mechanisms for selecting and configuring groups of components.</p><pre>builder.RegisterAssemblyTypes(typeof(OrderService).Assembly)<br>    .Where(type =&gt; type.Name.EndsWith(&quot;Service&quot;))<br>    .AsImplementedInterfaces();</pre><p>Here, Autofac scans an assembly and automatically registers types matching a convention instead of requiring each service to be registered individually. This can be useful in large applications where registrations follow consistent conventions across multiple modules.</p><p>For applications that only need assembly scanning or decorators, a focused library such as Scrutor can extend the built-in container without requiring a full container replacement. The case for Autofac becomes stronger when several advanced container capabilities are needed together.</p><p><strong>Conclusion: Which One Should You Choose?</strong></p><ul><li><strong>Start with the built-in container: </strong>For most modern .NET applications, it provides everything you need for constructor injection, lifetime management, scopes, keyed services, and standard registration patterns.</li><li><strong>Reach for Autofac when you have a concrete requirement that justifies it: </strong>Runtime interception, property injection, richer lifetime scopes, advanced registration conventions, or container-level modularization can be legitimate reasons.</li><li><strong>But don’t introduce Autofac simply because the application is large: </strong>A third-party container adds another abstraction, dependency, and set of concepts that your team needs to understand and maintain. The feature should justify the complexity.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a66ce4cd260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Advanced .NET DI Tricks and Anti-Patterns Every Developer Should Master]]></title>
            <link>https://satyampushkar.medium.com/3-advanced-net-di-tricks-and-anti-patterns-every-developer-should-master-aa070ca49e37?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa070ca49e37</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 17:58:41 GMT</pubDate>
            <atom:updated>2026-10-05T17:58:41.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUA4bKaKkybMgVIawnP2hw.png" /></figure><p>Setting up basic Dependency Injection (DI) in .NET is straightforward — register your abstractions in Program.cs and let constructor injection handle object creation.</p><p>However, as applications grow in complexity, developers frequently encounter tricky architectural edge cases:</p><ul><li>Needing to resolve a service while configuring the application in Program.cs.</li><li>Needing to use DI-dependent services in C# Attributes such as MVC Action Filters.</li><li>Constructing objects that require a mix of DI-registered services and runtime data.</li></ul><p>When facing these scenarios, it is easy to accidentally fall into anti-patterns that introduce duplicate service instances, tight coupling, or hidden dependencies.</p><p>In this article, we’ll examine <strong>3 advanced .NET DI techniques and anti-patterns</strong>, look at why common workarounds fail, and implement clean, production-ready solutions.</p><h3>1. The BuildServiceProvider() Anti-Pattern</h3><h3>Problem Statement</h3><p>Imagine you are configuring a custom service or options pattern in Program.cs. To configure your service options, you need to read a setting from a database or execute logic from another service.</p><p>To get hold of that dependency during startup, developers often write something like this:</p><pre>// ❌ BAD: Calling BuildServiceProvider() inside Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddSingleton&lt;IConfigService, ConfigService&gt;();<br>// Building an early, temporary ServiceProvider<br>var tempProvider = builder.Services.BuildServiceProvider();<br>var configService = tempProvider.GetRequiredService&lt;IConfigService&gt;();<br>// Using the service to configure another component<br>builder.Services.Configure&lt;MyOptions&gt;(options =&gt;<br>{<br>    options.ApiKey = configService.GetApiKey();<br>});</pre><p>At first glance, this solves the immediate problem. But under the hood, calling BuildServiceProvider() during service configuration is a major anti-pattern.</p><h3>Why is this dangerous?</h3><p>Calling BuildServiceProvider() manually creates a separate ServiceProvider from the one the application will ultimately use.</p><p>This causes two severe issues:</p><ol><li><strong>Duplicate Singletons:</strong> Any Singleton resolved from tempProvider is tied to that temporary container. When ASP.NET Core builds its actual application container later, it will create a <strong>second instance</strong> of your &quot;Singleton&quot;.</li><li><strong>Resource &amp; Memory Overhead:</strong> Creating multiple service providers can result in duplicate service instances and additional resource usage. If the temporary provider isn’t disposed, services it created that implement IDisposable or IAsyncDisposable may not be disposed properly.</li></ol><h3>The Clean Solution</h3><p>Instead of building a temporary provider, use the OptionsBuilder.Configure overloads that allow registered services to be resolved from DI during options configuration:</p><pre>// ✅ GOOD: Using OptionsBuilder with DI dependency resolution<br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddSingleton&lt;IConfigService, ConfigService&gt;();<br>// Configure options using the IServiceProvider passed by the framework<br>builder.Services.AddOptions&lt;MyOptions&gt;()<br>    .Configure&lt;IConfigService&gt;((options, configService) =&gt;<br>    {<br>        options.ApiKey = configService.GetApiKey();<br>    });</pre><p>By allowing the framework to resolve IConfigService from DI and pass it to the configuration delegate, you avoid creating a separate service provider entirely.</p><h3>2. Dependency Injection in C# Attributes (ServiceFilter vs. TypeFilter)</h3><h3>Problem Statement</h3><p>Action Filters in ASP.NET Core are a powerful way to run code before or after an action method executes. Suppose you want to build a custom AuditLoggingFilter that logs user actions using a scoped IAuditRepository.</p><p>Because attributes in C# are metadata applied at compile-time, their constructor parameters must be constant values supplied at the usage site. You <strong>cannot</strong> inject DI services directly into an attribute constructor:</p><pre>// ❌ DOES NOT COMPILE: Attributes cannot receive DI parameters directly<br>public class AuditLoggingAttribute : ActionFilterAttribute<br>{<br>    private readonly IAuditRepository _repository; // Cannot be passed via [AuditLogging]<br>    public AuditLoggingAttribute(IAuditRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>}</pre><h3>The Solution: [ServiceFilter] vs. [TypeFilter]</h3><p>ASP.NET Core provides two built-in filter attributes that solve this problem by bridging C# attributes with the DI container.</p><h4>Option A: [ServiceFilter]</h4><p>ServiceFilterAttribute resolves the filter instance directly from the DI container.</p><ul><li><strong>Requirement:</strong> The filter class itself <strong>must be registered</strong> in Program.cs.</li></ul><pre>// 1. Define the filter class<br>public class AuditLoggingFilter : IAsyncActionFilter<br>{<br>    private readonly IAuditRepository _repository;<br><br>    public AuditLoggingFilter(IAuditRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        // Audit logging logic...<br>        await next();<br>    }<br>}<br>// 2. Register the filter in Program.cs<br>builder.Services.AddScoped&lt;AuditLoggingFilter&gt;();<br>// 3. Apply on Controller using [ServiceFilter]<br>[ServiceFilter(typeof(AuditLoggingFilter))]<br>public class OrdersController : ControllerBase { }\</pre><h4>Option B: [TypeFilter]</h4><p>TypeFilterAttribute is similar, but it does <strong>not</strong> resolve the filter directly from the container. Instead, it creates the filter using the framework&#39;s type-activation infrastructure while resolving its dependencies from DI.</p><ul><li><strong>Requirement:</strong> The filter class does <strong>not</strong> need to be registered in Program.cs.</li><li><strong>Bonus:</strong> It can accept additional constructor arguments alongside DI dependencies.</li></ul><pre>// Filter definition remains the same (no registration in Program.cs required!)<br>// Apply on Controller using [TypeFilter]<br>[TypeFilter(typeof(AuditLoggingFilter))]<br>public class OrdersController : ControllerBase { }</pre><p><em>How the resolution differs</em></p><p>With <strong>[ServiceFilter]</strong>, ASP.NET Core retrieves the filter from the DI container. The filter type therefore needs to be registered in DI, and its constructor dependencies are resolved by the container.</p><p>With <strong>[TypeFilter]</strong>, the filter type itself doesn&#39;t need to be registered. ASP.NET Core creates the filter using its type-activation infrastructure while resolving its constructor dependencies from DI.</p><p><em>What about custom arguments?</em></p><p>TypeFilterAttribute can also accept constructor arguments through its Arguments property. This allows a filter to combine DI-provided services with explicitly supplied values.</p><pre>[TypeFilter(typeof(AuditLoggingFilter), Arguments = new object[] { &quot;Orders&quot; })]<br>public class OrdersController : ControllerBase { }</pre><h3>Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*5UzLZ28jzshHlH-fZK36WQ.png" /></figure><h3>3. Hybrid Object Creation with ActivatorUtilities</h3><h3>Problem Statement</h3><p>Consider a background worker or domain service that requires both:</p><ol><li>Services registered in DI (e.g., ILogger&lt;InvoiceGenerator&gt;, IInvoiceRepository).</li><li>Runtime parameters unique to a specific operation (e.g., string invoiceId, DateTime dueDate).</li></ol><p>Developers often resort to the <strong>Service Locator anti-pattern</strong> to solve this — passing IServiceProvider into the class and pulling dependencies manually:</p><pre>// ❌ BAD: Service Locator Anti-Pattern<br>public class InvoiceGenerator<br>{<br>    private readonly IInvoiceRepository _repository;<br>    private readonly string _invoiceId;<br><br>    public InvoiceGenerator(IServiceProvider provider, string invoiceId)<br>    {<br>        // Hides dependencies and couples class to IServiceProvider<br>        _repository = provider.GetRequiredService&lt;IInvoiceRepository&gt;();<br>        _invoiceId = invoiceId;<br>    }<br>}</pre><p>As we know, Service Locator hides dependencies, hurts testability, and mixes Inversion of Control strategies.</p><h3>The Clean Solution: ActivatorUtilities</h3><p>.NET provides ActivatorUtilities, a helper class designed for creating objects that combine DI-resolved dependencies with explicit constructor arguments.</p><p>ActivatorUtilities.CreateInstance&lt;T&gt; creates an instance by resolving dependencies from an IServiceProvider while accepting additional constructor arguments supplied explicitly:</p><pre>// ✅ GOOD: Clean Constructor Injection with explicit requirements<br>public class InvoiceGenerator<br>{<br>    private readonly IInvoiceRepository _repository;<br>    private readonly ILogger&lt;InvoiceGenerator&gt; _logger;<br>    private readonly string _invoiceId;<br><br>    // Clear, discoverable constructor requirements<br>    public InvoiceGenerator(<br>        IInvoiceRepository repository,<br>        ILogger&lt;InvoiceGenerator&gt; logger,<br>        string invoiceId)<br>    {<br>        _repository = repository;<br>        _logger = logger;<br>        _invoiceId = invoiceId;<br>    }<br>    public void Generate() { ... }<br>}<br>// in programm.cs<br>builder.Services.AddTransient&lt;InvoiceGenerator&gt;();</pre><p>Now, when you need to instantiate InvoiceGenerator at runtime, use ActivatorUtilities:</p><pre>public class InvoiceProcessingWorker<br>{<br>    private readonly IServiceScopeFactory _scopeFactory;<br><br>    public InvoiceProcessingWorker(IServiceScopeFactory scopeFactory)<br>    {<br>        _scopeFactory = scopeFactory;<br>    }<br><br>    public void ProcessInvoice(string invoiceId)<br>    {<br>        using var scope = _scopeFactory.CreateScope();<br><br>        var generator = ActivatorUtilities.CreateInstance&lt;InvoiceGenerator&gt;(<br>            scope.ServiceProvider,<br>            invoiceId);<br><br>        generator.Generate();<br>    }<br>}</pre><p>ActivatorUtilities pulls registered dependencies from the current DI scope and uses the supplied invoiceId as the runtime argument.</p><h3>Summary</h3><p>Mastering these advanced DI techniques helps keep your ASP.NET Core applications clean, performant, and bug-free:</p><ol><li><strong>Avoid </strong><strong>BuildServiceProvider() in Startup:</strong> Use AddOptions&lt;T&gt;().Configure&lt;IService&gt;() to resolve setup dependencies safely without creating duplicate containers.</li><li><strong>Bridge Attributes and DI:</strong> Use [ServiceFilter] (for container-registered filters) or [TypeFilter] (for unregistered filters or custom arguments) to supply dependencies to C# attributes.</li><li><strong>Use </strong><strong>ActivatorUtilities for Hybrid Creation:</strong> Combine runtime arguments with DI dependencies cleanly without falling into the Service Locator anti-pattern.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa070ca49e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Garbage Collection Won’t Save Your .NET App from DI Leaks]]></title>
            <link>https://satyampushkar.medium.com/why-garbage-collection-wont-save-your-net-app-from-di-leaks-ab6179dab259?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6179dab259</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 16:16:01 GMT</pubDate>
            <atom:updated>2026-09-24T16:16:01.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JXiqevf1oohWVoNcqMyxQ.png" /></figure><p>In modern .NET development, we often rely on the <strong>Garbage Collector (GC)</strong> to clean up unused memory automatically. At the same time, we rely on the built-in <strong>Dependency Injection (DI)</strong> container (IServiceProvider) to manage object creation, lifetimes, and disposal.</p><p>Because the framework handles both memory and dependencies seamlessly in most cases, it is easy to assume that once an object falls out of local scope, the GC will sweep it away.</p><p>However, when Dependency Injection and Garbage Collection interact in subtle ways, unexpected memory retention and memory leaks can creep into your application.</p><p>In this article, we’ll look under the hood to see how the GC views objects managed by the DI container across all three service lifetimes (<strong>Transient</strong>, <strong>Scoped</strong>, and <strong>Singleton</strong>), examine how DI can contribute to memory retention, memory leaks, and unbounded memory growth, and learn how to prevent and diagnose them.</p><h3>The Invisible Link: How the GC Sees the DI Container</h3><p>To understand memory leaks in .NET DI, we first need to recall how the Garbage Collector determines what to keep and what to clean up:</p><ol><li><strong>GC Roots:</strong> The GC traverses your application’s object graph starting from <strong>GC Roots</strong> (such as static variables, active CPU registers, or running thread stacks).</li><li><strong>Reachability:</strong> If an object is reachable through a chain of references leading back to a GC Root, <strong>it is considered alive, and the GC is forbidden from collecting it.</strong></li></ol><h3>DI Lifetime ≠ Garbage Collection Lifetime</h3><p>DI lifetimes and GC lifetimes are related, but they are not the same thing.</p><p><strong>Transient</strong>, <strong>Scoped</strong>, and <strong>Singleton </strong>describe how the DI container manages service instances. <strong>The Garbage Collector</strong>, on the other hand, determines whether an object can be collected based on whether it remains reachable.</p><p>A service can therefore have a short DI lifetime but still remain in memory longer if another object retains a reference to it.</p><h3>Memory Leak vs. Memory Retention vs. Unbounded Growth</h3><p>These terms are related, but they are not interchangeable.</p><ol><li><strong>Memory retention</strong> means an object remains reachable because something still holds a reference to it. The object may be retained intentionally or unintentionally.</li><li>A <strong>memory leak</strong> occurs when an application continues to retain objects that it no longer needs, preventing the Garbage Collector from reclaiming their memory.</li><li><strong>Unbounded memory growth</strong> occurs when an application continues adding data to an in-memory structure without a limit, expiration, or eviction strategy. This can eventually lead to excessive memory usage or an `OutOfMemoryException`.</li></ol><p>For example:</p><ul><li>A DI container retaining a disposable transient until the root container is disposed is <strong>memory retention</strong> caused by the container’s disposal tracking.</li><li>A long-lived event publisher retaining a short-lived subscriber that is no longer needed can become a <strong>memory leak</strong>.</li><li>A Singleton Dictionary that continuously accumulates entries without eviction is <strong>unbounded memory growth</strong>.</li></ul><blockquote>The practical question is therefore not simply — “Why is memory usage increasing?”</blockquote><blockquote>Instead, ask — “<strong>Which objects are still reachable, and why are they still being retained?</strong>”</blockquote><h3>How the Root Container Retains Objects</h3><p>When your ASP.NET Core application boots up, the root DI container (IServiceProvider) is created and typically lives for the entire lifetime of the application.</p><p>The important point is not that the DI container is itself a special GC Root, but that objects retained by the root container remain <strong>reachable from GC Roots</strong>.</p><p>Crucially, when the DI container creates an object that implements IDisposable or IAsyncDisposable, it keeps a hard reference to that object so it can automatically call Dispose() when its scope or the application shuts down.</p><p>As long as the container holds that reference, the GC sees a living reference connected to a GC Root — which means <strong>the object can never be garbage collected until the container releases its reference</strong>.</p><h3>1. Transient Lifetimes: The “Disposable Transient” Trap</h3><p>A Transient service is created each time it is requested from the container. It is commonly used for services that don’t need to be shared between consumers.</p><pre>builder.Services.AddTransient&lt;IExportService, ExportService&gt;();</pre><p>Normally, once no live references remain to the transient instance, it becomes <strong>eligible for garbage collection</strong>.</p><h3>The Problem: Resolving IDisposable Transients from the Root Container</h3><p>If your transient service implements IDisposable, the DI container tracks it to guarantee it will be disposed of.</p><p>If you resolve a disposable transient service directly from the <strong>root container</strong> (such as app.Services in Program.cs or inside a background job without creating a scope), the root container stores a reference to every single transient instance created.</p><pre>// BAD: Resolving disposable transient from the root container repeatedly<br>public void ProcessJobs(IServiceProvider rootProvider)<br>{<br>    for (int i = 0; i &lt; 10000; i++)<br>    {<br>        // Creates a new ExportService instance on every iteration<br>        var exporter = rootProvider.GetRequiredService&lt;IExportService&gt;();<br>        exporter.DoWork();<br>        // Even if &#39;exporter&#39; goes out of local scope,<br>        // the root container holds a reference to it in its tracking list!<br>    }<br>}</pre><h3>The GC Impact</h3><p>Because these instances were resolved from the root container, the container will not release its references until the application shuts down.</p><p>Even though your method finished and no local code points to exporter, the root container&#39;s internal IDisposable list keeps a hard reference to all 10,000 instances. The GC cannot collect a single one of them, resulting in <strong>steadily increasing memory usage because the container continues to retain those instances</strong>.</p><h3>2. Scoped Lifetimes: Request Scope Boundaries &amp; Captive Dependencies</h3><p>A <strong>Scoped</strong> service is created once per client HTTP request or logical operation scope.</p><pre>builder.Services.AddScoped&lt;IOrderRepository, OrderRepository&gt;();</pre><p>In ASP.NET Core, an IServiceScope is created at the beginning of each HTTP request. The scope container acts as a short-lived mini container.</p><h3>The Clean Path</h3><p>When an HTTP request finishes, ASP.NET Core disposes of the request scope. The scope calls Dispose() on all tracked IDisposable objects created during that request and drops its internal references.</p><p>Once those references are dropped, objects that are no longer referenced elsewhere become unreachable from any GC Root and become eligible for garbage collection.</p><pre>[ Incoming Request ] ──► Creates IServiceScope<br>                             │<br>                             ├──► Instantiates DbContext &amp; Services<br>                             │<br>[ Request Ends ]     ──► Disposes IServiceScope<br>                             │<br>                             └──► References Dropped<br>                                      │<br>                                      ▼<br>                              Objects eligible for GC</pre><h3>The Problem: Captive Dependencies</h3><p>A <strong>Captive Dependency</strong> occurs when a service with a longer lifetime (like a <strong>Singleton</strong>) captures a service with a shorter lifetime (like a <strong>Scoped</strong> service) via constructor injection.</p><p>In the default Development configuration, .NET’s scope validation detects this invalid lifetime relationship and throws an exception rather than allowing the application to start normally.</p><p>However, if scope validation is disabled — or if a similar lifetime mismatch is created through another resolution path — the longer-lived service can retain the shorter-lived dependency for much longer than intended.</p><pre>// BAD: This lifetime mismatch is rejected when scope validation is enabled<br>public class CacheWarmupService // Registered as Singleton<br>{<br>    private readonly IOrderRepository _repository; // Registered as Scoped<br><br>    public CacheWarmupService(IOrderRepository repository)<br>    {<br>        _repository = repository; // Captured!<br>    }<br>}</pre><h3>The GC Impact</h3><p>Once the Singleton captures the Scoped dependency, the Singleton remains alive for the lifetime of the application.</p><p>Because the Singleton holds a reference to _repository, and _repository holds a reference to the DbContext, the DbContext and objects still referenced by its change tracker can also remain reachable for the lifetime of the Singleton. This can cause the DbContext to retain more state than intended and lead to increasing memory usage over time.</p><h3>3. Singleton Lifetimes: Unbounded Collections &amp; Event Leaks</h3><p>A <strong>Singleton</strong> service is created once (either on startup or upon first request) and is typically retained for the entire lifespan of the application.</p><pre>builder.Services.AddSingleton&lt;IUserCache, UserCache&gt;();</pre><p>Because a Singleton remains alive for the lifetime of the application, any objects it <strong>continues to reference</strong> also remain reachable for as long as those references are retained.</p><h3>Memory Problems to Watch Out For in Singletons:</h3><h4>1. Unbounded In-Memory Collections</h4><p>If a Singleton maintains an internal List&lt;T&gt; or Dictionary&lt;TKey, TValue&gt; to cache data or log events without an eviction strategy or maximum size limit, that collection will grow indefinitely until the application runs out of memory (OutOfMemoryException).</p><pre>public class UserCache : IUserCache // Singleton<br>{<br>    // Danger: Unbounded cache growth<br>    private readonly ConcurrentDictionary&lt;string, UserDto&gt; _cache = new();<br><br>    public void AddUser(UserDto user) =&gt; _cache[user.Id] = user;<br>    // Without expiration or cache eviction, items stay in memory forever!<br>}</pre><h4>2. C# Event Subscription Leaks</h4><p>When an object subscribes to an event on another object, the event publisher holds a reference to the subscriber via its delegate invocation list.</p><p>If a short-lived object subscribes to an event published by a long-lived Singleton and does not unsubscribe, the Singleton’s delegate reference can prevent the short-lived object from being garbage collected.</p><pre>public class OrderNotifier // Short-lived / Scoped<br>{<br>    public OrderNotifier(IGlobalConfigSingleton config)<br>    {<br>        // BAD: Subscribing to a Singleton event without unsubscribing!<br>        // The Singleton &#39;config&#39; publisher now holds a reference to this OrderNotifier instance.<br>        config.OnConfigChanged += HandleConfigChange;<br>    }<br><br>    private void HandleConfigChange(object sender, EventArgs e) { ... }<br>}</pre><p>The important part is the reference direction: the long-lived Singleton event publisher holds a delegate that references the short-lived OrderNotifier. As long as the subscription remains, the OrderNotifier stays reachable and cannot be collected.</p><h3>Summary Matrix: DI Lifetimes vs. GC Behavior</h3><p>To help you visualize how DI and Garbage Collection interact across service lifetimes, keep this reference cheat sheet in mind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxuEFq0Qja9K-469k5TDBw.png" /></figure><h3>Preventing DI-Related Memory Problems</h3><h4>Prevent</h4><p>The first line of defense is to prevent unintended object retention:</p><ol><li><strong>Respect DI lifetime boundaries</strong>: Avoid resolving disposable transients from the root container and avoid longer-lived services capturing shorter-lived dependencies.</li><li><strong>Bound in-memory data</strong>: Singleton caches, dictionaries, queues, and collections should have an explicit maximum size, expiration policy, or eviction strategy.</li><li><strong>Manage event subscriptions</strong>: When a short-lived object subscribes to an event published by a longer-lived object, unsubscribe when the subscriber is no longer needed.</li><li><strong>Create explicit scopes for background work</strong>: Long-running workers should create and dispose an appropriate scope for each unit of work when scoped services are required.</li><li><strong>Set realistic container memory requests and limits:</strong> In containerized environments, configure appropriate memory requests for scheduling and memory limits to prevent a runaway process from consuming unbounded node resources.</li><li><strong>Enable DI validation:</strong> Enable ValidateScopes and ValidateOnBuild during development and testing so invalid DI configurations can be detected early</li></ol><h4>Detect</h4><p>In a Cloud Native environment, memory problems should be detected through application and runtime metrics rather than waiting for the application to fail. Useful signals include:</p><ul><li>Container or process working-set memory</li><li>Managed GC heap size</li><li>Allocation rate</li><li>Container restarts or OOM kills</li></ul><p>A rising working set does not automatically mean a memory leak. Look for sustained memory growth under a similar workload, especially when the managed heap remains high after garbage collections. For .NET applications, runtime metrics such as dotnet.process.memory.working_set and dotnet.gc.last_collection.heap.size can help distinguish overall process memory from managed heap usage.</p><h4>Diagnose</h4><p>Once a memory problem is confirmed, the next question is: <strong>What is retaining the objects?</strong></p><p>For .NET applications, diagnostic tools can help answer that question:</p><ul><li>dotnet-counters can monitor runtime and memory metrics.</li><li>dotnet-dump can capture and analyze process dumps.</li><li>dotnet-gcdump can help inspect managed heap information.</li><li>dotnet-monitor can collect metrics and diagnostic artifacts from applications running in production environments.</li></ul><p>A typical investigation looks like:</p><pre>Memory usage increasing<br>        ↓<br>Confirm managed heap growth<br>        ↓<br>Compare heap/object counts over time<br>        ↓<br>Capture a dump<br>        ↓<br>Identify objects that remain unexpectedly alive<br>        ↓<br>Inspect their GC roots / reference paths<br>        ↓<br>Identify the retaining object<br>        ↓<br>Fix the lifetime, cache, event subscription, or reference</pre><h4>A Cloud Native Memory Leak Scenario</h4><p>Consider a .NET API running in Kubernetes with a memory limit of <strong>512 MB</strong>.</p><ul><li>Initially: <strong>180 MB</strong></li><li>After several hours: <strong>300 MB</strong></li><li>Later: <strong>450 MB</strong></li><li>Eventually: the container reaches its memory limit and may be terminated due to an OOM condition.</li></ul><p>A pod restart may temporarily make the problem disappear:</p><pre>450 MB → Pod restart → 180 MB</pre><p>But the restart did <strong>not</strong> fix the leak. It only removed the process and all of the objects it was retaining.</p><p>This is why monitoring memory usage and restart patterns is important in Cloud Native applications. A recurring pattern of increasing memory followed by container restarts can be an important signal that an application needs deeper memory investigation.</p><h3>Final Takeaway</h3><p>Garbage Collection can reclaim objects that are no longer reachable, but it cannot determine whether your application <strong>still needs</strong> an object.</p><p>That responsibility ultimately comes from how your application manages references, DI lifetimes, scopes, caches, events, and other long-lived objects.</p><blockquote>DI controls how long services are managed by the container; the GC controls when unreachable objects can be reclaimed.</blockquote><p>When investigating memory problems, don’t just ask <strong>“Why is memory increasing?”</strong>. Ask: <strong>“Which objects are still reachable, and what is keeping them alive?”</strong></p><p>That question usually takes you from a memory symptom to the actual retaining reference — and ultimately to the fix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6179dab259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Captive Dependency” Trap: Understanding .NET DI Lifetimes]]></title>
            <link>https://satyampushkar.medium.com/the-captive-dependency-trap-understanding-net-di-lifetimes-c8243a4cf0f8?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8243a4cf0f8</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 04:16:01 GMT</pubDate>
            <atom:updated>2026-09-23T04:16:01.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqV04T5Ookj3z378d-1Npw.png" /></figure><p>In modern .NET applications, Dependency Injection (DI) is the backbone of clean, maintainable architecture. We rely on the built-in IoC container to manage service creation and disposal automatically.</p><p>However, as applications grow into microservices and background processors, subtle lifetime misconfigurations can sneak into production. One of the most common and dangerous errors is the <strong>Captive Dependency</strong>.</p><p>In this article, we’ll look at what a captive dependency is, why it causes resource retention and runtime problems, and how to fix it cleanly in your .NET applications.</p><h3>Problem Statement</h3><p>Imagine you are building a background processing service in a food delivery microservice. You have a BackgroundService called OrderProcessingWorker that wakes up periodically to fetch pending orders from the database and send notifications.</p><p>To handle database operations, you inject your Entity Framework Core OrderDbContext or IOrderRepository (registered as <strong>Scoped</strong>) into your OrderProcessingWorker (registered as a <strong>Singleton</strong>).</p><p>Here is what the straightforward code looks like:</p><pre>// BAD: Injecting a Scoped service directly into a Singleton<br>public class OrderProcessingWorker : BackgroundService<br>{<br>    private readonly IOrderRepository _orderRepository;<br><br>    public OrderProcessingWorker(IOrderRepository orderRepository)<br>    {<br>        _orderRepository = orderRepository;<br>    }<br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            var pendingOrders = await _orderRepository.GetPendingOrdersAsync();<br>            // Process orders...<br>            await Task.Delay(5000, stoppingToken);<br>        }<br>    }<br>}</pre><p>At first glance, the code looks perfectly reasonable. However, with the default scope validation settings enabled in Development, the application will fail during service-provider validation, reporting that a scoped service cannot be consumed from a singleton.</p><h3>What goes wrong?</h3><p>A BackgroundService is registered as a <strong>Singleton</strong> by the hosted-service infrastructure, so the worker typically lives for the lifetime of the application. EF Core&#39;s DbContext and repository layers are typically registered as <strong>Scoped</strong>—intended to live only for the duration of a single HTTP request or unit of work.</p><p>When you inject IOrderRepository into OrderProcessingWorker, the Singleton holds onto that single instance of the Scoped service for the entire lifetime of the application.</p><p>This causes severe runtime issues:</p><ol><li><strong>Extended lifetime and state retention:</strong> The DbContext can remain alive for the lifetime of the singleton instead of being disposed at the end of a unit of work. Because DbContext maintains change-tracking state, long-lived usage can cause memory growth and stale state, and can violate the intended unit-of-work lifetime.</li><li><strong>Concurrency issues:</strong> DbContext isn&#39;t thread-safe. If the captured repository or its underlying DbContext is used concurrently—for example, when processing multiple operations in parallel—it can result in runtime exceptions and corrupted application behavior.</li></ol><h3>What is a Captive Dependency?</h3><p>A <strong>Captive Dependency</strong> occurs when a service with a longer lifetime captures a service with a shorter lifetime, artificially extending the shorter service’s lifetime to match its own.</p><p>To keep things clear, let’s quickly revisit .NET’s three service lifetimes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*wkjquWMeXY2natc6j7uAvA.png" /></figure><h3>The Lifetime Hierarchy Rule</h3><p>A longer-lived service should not directly depend on a service whose intended lifetime is shorter than its own:</p><ul><li>✅ <strong>Singleton → </strong>Singleton</li><li>✅ <strong>Scoped</strong> <strong>→</strong> Scoped / Singleton</li><li>✅ <strong>Transient → </strong>Transient / Scoped / Singleton</li><li>❌ <strong>Singleton → </strong>Scoped <em>(Captive Dependency!)</em></li><li>⚠️<strong>Singleton</strong> <strong>→</strong> Transient (Generally valid, but requires care when the transient is disposable or relies on short-lived state).</li></ul><h3>Why BackgroundService is Different</h3><p>BackgroundService is a long-lived hosted service. Unlike an HTTP request, its execution loop does not automatically create a new dependency-injection scope for each iteration.</p><p>Therefore, if the worker needs scoped services such as an EF Core DbContext, it must explicitly create a scope for each unit of work.</p><h3>The Solution: Manual Scope Creation with IServiceScopeFactory</h3><p>To fix this issue in hosted background services or singletons, you should <strong>not</strong> inject the scoped dependency directly into the constructor.</p><p>Instead, inject IServiceScopeFactory, manually create an IServiceScope for each iteration or unit of work, and resolve your scoped service inside that scope.</p><p>The scope should be created around the unit of work, not around the lifetime of the background worker. When the using block finishes, the scope is disposed, along with the disposable services resolved from that scope, including the DbContext.</p><p>Here is the updated implementation:</p><pre>// GOOD: Creating a dedicated scope inside the background loop<br>public class OrderProcessingWorker : BackgroundService<br>{<br>    private readonly IServiceScopeFactory _scopeFactory;<br>    private readonly ILogger&lt;OrderProcessingWorker&gt; _logger;<br>    <br>    public OrderProcessingWorker(<br>        IServiceScopeFactory scopeFactory,<br>        ILogger&lt;OrderProcessingWorker&gt; logger)<br>    {<br>        _scopeFactory = scopeFactory;<br>        _logger = logger;<br>    }<br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            // Create a short-lived scope for this execution pass<br>            using (var scope = _scopeFactory.CreateScope())<br>            {<br>                var orderRepository = scope.ServiceProvider<br>                    .GetRequiredService&lt;IOrderRepository&gt;();<br>                var pendingOrders = await orderRepository.GetPendingOrdersAsync();<br>                _logger.LogInformation(&quot;Processing {Count} pending orders&quot;, pendingOrders.Count);<br>                // Process orders...<br>            } // Scope is disposed here, cleaning up DbContext automatically<br>            await Task.Delay(5000, stoppingToken);<br>        }<br>    }<br>}</pre><p>Here, resolving IOrderRepository from the scoped IServiceProvider is intentional. The background worker needs to resolve the dependency from the newly created scope so that it—and its own scoped dependencies, such as DbContext—share that scope and are disposed when the unit of work completes.</p><h3>Pro-Tip: Catching Captive Dependencies at Startup</h3><p>You don’t have to rely on manual code reviews to catch these issues. The default .NET WebApplicationBuilder includes a feature called <strong>Scope Validation</strong>.</p><p>In the <strong>Development</strong> environment, scope validation is enabled automatically.If a Singleton attempts to consume a Scoped service while scope validation is enabled, .NET throws an InvalidOperationException when the service provider validates the registrations.</p><p>If you want to explicitly enable scope validation or turn it on in staging environments, configure it in Program.cs:</p><pre>var builder = WebApplication.CreateBuilder(args);<br>// Force scope validation on Host building<br>builder.Host.UseDefaultServiceProvider((context, options) =&gt;<br>{<br>    options.ValidateScopes = true;<br>    options.ValidateOnBuild = true; // Validate registrations when building the provider<br>});</pre><p>ValidateScopes helps detect scoped services being resolved from the root scope or consumed by singletons. ValidateOnBuild validates the service configuration when the provider is built, allowing configuration problems to surface earlier.</p><h3>Summary</h3><p>Captive dependencies are lifetime misconfigurations that can lead to excessive resource retention, stale state, and concurrency problems when the captured service isn’t designed for long-lived or concurrent use. Remember these core takeaways:</p><ol><li>Never inject Scoped services directly into Singleton services such as BackgroundService.</li><li><strong>Use </strong><strong>IServiceScopeFactory</strong> to create short-lived scopes when working inside background tasks.</li><li><strong>Enable </strong><strong>ValidateOnBuild and </strong><strong>ValidateScopes</strong> during development so .NET catches these errors before they reach production.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8243a4cf0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Dependency Injection in .NET: From Basics to Constructor Resolution]]></title>
            <link>https://satyampushkar.medium.com/demystifying-dependency-injection-in-net-from-basics-to-constructor-resolution-333d34c11f24?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/333d34c11f24</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 18:40:17 GMT</pubDate>
            <atom:updated>2026-09-21T18:40:17.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWoIOIHw1uZTA1dHrp6vtg.png" /></figure><p>When building scalable application architectures in .NET, Dependency Injection (DI) is one of the first concepts every developer encounters. We register services in Program.cs, add dependencies to our constructors, and somehow receive fully constructed instances at runtime.</p><p>But <em>what is actually happening under the hood when .NET resolves a service or ASP.NET Core creates a controller</em>? Who actually calls the constructor, how does the container choose which constructor to invoke, and how does it construct a complex object graph?</p><p>In this article, we’ll break down the fundamentals of DI, explore how it’s integrated into .NET, and step through the internal mechanics of constructor injection.</p><p><strong>Problem Statement: The Danger of </strong>new</p><p>Imagine you are building an order checkout system. Your OrderService needs to process payments via PaymentProcessor and send emails via EmailNotifier.</p><p>In a naive implementation, OrderService creates its own dependencies directly:</p><pre>// BAD: Tightly coupled dependencies created with &#39;new&#39;<br>public class OrderService<br>{<br>    private readonly PaymentProcessor _paymentProcessor;<br>    private readonly EmailNotifier _emailNotifier;<br><br>    public OrderService()<br>    {<br>        _paymentProcessor = new PaymentProcessor();<br>        _emailNotifier = new EmailNotifier();<br>    }<br>    public void Checkout(Order order)<br>    {<br>        _paymentProcessor.Process(order.Amount);<br>        _emailNotifier.SendReceipt(order.CustomerEmail);<br>    }<br>}</pre><p>While this code works initially, instantiating objects directly using the new keyword creates tightly coupled code that is difficult to unit test, maintain, and extend. You cannot easily mock PaymentProcessor in unit tests, nor can you swap implementations without modifying OrderService.</p><p><strong>Inversion of Control (IoC) &amp; DIP</strong></p><p>To solve this, we apply <strong>Inversion of Control</strong> (IoC) — a design principle where the control of object creation and lifetime management is inverted from the class itself to an external framework or container.</p><p>It helps to distinguish three closely related terms that are often used interchangeably:</p><ul><li><strong>Dependency Inversion Principle (DIP)</strong>: An architectural design principle stating that high-level modules should depend on abstractions rather than concrete details. DIP influences how dependencies are structured and where abstractions are introduced.</li><li><strong>Inversion of Control (IoC)</strong>: A broad design principle where control of execution or object creation is inverted. IoC defines the <em>direction</em> of control.</li><li><strong>Dependency Injection (DI)</strong>: A technique for supplying a class’s dependencies from outside the class — typically through constructor parameters.</li></ul><p><strong>Dependency Injection in .NET</strong></p><p>In .NET, objects a class requires are “injected” into its constructor rather than created internally. Constructor injection prevents classes from holding creation responsibilities and provides a clear, discoverable convention for expressing dependencies.</p><p>ASP.NET Core includes a built-in DI container. At application startup, services are registered with IServiceCollection. Once all services are configured, the application builds an IServiceProvider that resolves service instances at runtime.</p><pre>var builder = WebApplication.CreateBuilder(args);<br>// Registering services with the DI container<br>builder.Services.AddScoped&lt;IOrderRepository, OrderRepository&gt;();<br>builder.Services.AddTransient&lt;IPaymentProcessor, PaymentProcessor&gt;();<br>builder.Services.AddSingleton&lt;IEmailNotifier, EmailNotifier&gt;();</pre><p><strong>The Three Service Lifetimes</strong></p><p>When registering services in .NET, you specify a service lifetime that tells the container how to manage creation and reuse:</p><ul><li><strong>Transient</strong> (AddTransient): A new instance is created every time the service is requested from the container. Best suited for lightweight, stateless components.</li><li><strong>Scoped </strong>(AddScoped): One instance is created per scope. In ASP.NET Core web applications, a scope is typically created for each HTTP request.</li><li><strong>Singleton </strong>(AddSingleton): A single instance is created and reused for the lifetime of the service container. With a typical type-based registration such as AddSingleton&lt;T&gt;(), the instance is created the first time it is requested. When an implementation instance is supplied directly, that instance is used instead. Singleton services must be thread-safe.</li></ul><p>One important lifetime rule is that a singleton should not directly depend on a scoped service. A singleton lives for the application lifetime, while a scoped service normally lives for the lifetime of a scope, such as an HTTP request. Holding a scoped service inside a singleton can effectively promote the scoped service to the lifetime of the singleton. This is commonly referred to as a <strong>captive dependency</strong>.</p><p><strong>What Happens Internally During Constructor Injection?</strong></p><p>When a client requests a service or an HTTP request hits an API endpoint, ASP.NET Core resolves the required controller or handler using IServiceProvider. Here is the step-by-step internal process of how constructor injection resolves dependencies:</p><pre>[ Incoming Request ]<br>         │<br>         ▼<br>1. Inspect Top-Level Type (e.g., OrderController)<br>         │<br>         ▼<br>2. Discover Dependencies ──► Build Dependency Tree / Object Graph <br>         │<br>         ▼<br>3. Constructor Selection Algorithm (Select best public constructor)<br>         │<br>         ▼<br>4. Bottom-Up Instantiation (Resolve leaf dependencies first)<br>         │<br>         ▼<br>5. Track Object Lifetimes &amp; Manage Disposal (IDisposable)</pre><p><strong>Step 1: Discovering the Dependency Tree (Object Graph)</strong></p><p>When IServiceProvider is asked to resolve a top-level service (such as a controller), the DI system examines the service&#39;s constructor and determines which dependencies are required. It then recursively resolves those dependencies and their own dependencies, forming the object graph needed to construct the requested service.</p><p>Often, dependencies have dependencies of their own. For example, OrderController depends on IOrderService, which depends on IOrderRepository, which in turn depends on DbContext. The container recursively analyzes these relationships to determine how the requested service and its dependencies need to be constructed, forming a dependency graph (or object graph).</p><p>For example, the dependency graph might look like this:</p><pre>OrdersController<br>      ↓<br> OrderService<br>   ↙       ↘<br>OrderRepository  PaymentProcessor<br>     ↓<br>  DbContext</pre><p>The container uses this dependency graph to determine what needs to be resolved before it can construct OrdersController.</p><p><strong>Step 2: The Constructor Selection Algorithm</strong></p><p>What if a target class defines multiple public constructors? The built-in .NET service container applies a deterministic constructor selection strategy:</p><ul><li>The container inspects all public constructors on the target type.</li><li>It evaluates which constructor parameters can be satisfied by registered types in IServiceCollection.</li><li>It selects the public constructor with the most parameters whose dependencies can all be resolved by the container.</li><li>Ambiguity Handling: If multiple constructors have the same maximum number of resolvable parameters, the container cannot determine which constructor to use and throws an exception.</li></ul><p>For example, if a class has two public constructors and both are fully resolvable by the DI container, the constructor with the greater number of parameters is selected. If two constructors have the same maximum number of resolvable parameters, the container cannot determine which one to use and throws an exception.</p><p><strong>Note:</strong> Constructor parameters that aren’t provided by DI can have default values. In that case, the default value is used. All other constructor parameters must be resolvable by the container.</p><p><strong>Step 3: Bottom-Up Object Instantiation</strong></p><p>Once the constructor is selected, the container resolves the dependencies required by that constructor, recursively resolving their own dependencies as needed:</p><ul><li>It resolves the dependencies required by the selected constructor, recursively resolving their own dependencies as needed.</li><li>It passes these newly created instances into the constructors of parent objects (e.g., passing DbContext into OrderRepository).</li><li>Once the required dependencies have been resolved, the container invokes the selected constructor and returns the fully constructed top-level object (e.g., OrderController).</li></ul><p><strong>Step 4: Lifetime Tracking &amp; Automatic Disposal</strong></p><p>The container’s job doesn’t end at instantiation. It also tracks services it creates so it can manage their lifetimes and disposal:</p><ul><li><strong>Tracking</strong>: Scoped and Singleton instances are cached within their respective scope or root container so that subsequent resolutions reuse the same instance.</li><li><strong>Disposal</strong>: When the container creates a service that implements IDisposable or IAsyncDisposable, it tracks that service and disposes it when the relevant scope or container is disposed. Scoped services are typically disposed at the end of their scope, while singleton services are disposed when the root container is disposed. Services resolved from the container should generally not be manually disposed by the consuming class.</li></ul><p>One important ownership detail is that disposal is managed by the container for services that the container creates. For example, with AddSingleton&lt;MyService&gt;(), the container creates and manages the instance. In contrast, with AddSingleton(new MyService()), the instance is created outside the container, so the container does not take responsibility for disposing that instance.</p><p><strong>Clean Code Example: Putting It All Together</strong></p><p>Here is how a clean, decoupled implementation looks using constructor injection in ASP.NET Core:</p><pre>// 1. Abstractions<br>public interface IOrderService<br>{<br>    Task ProcessOrderAsync(Order order);<br>}<br><br>// 2. Implementation with Constructor Injection<br>public class OrderService : IOrderService<br>{<br>    private readonly IOrderRepository _repository;<br>    private readonly IPaymentProcessor _paymentProcessor;<br>    private readonly ILogger&lt;OrderService&gt; _logger;<br>    // Constructor injection: All dependencies explicitly declared<br>    public OrderService(<br>        IOrderRepository repository,<br>        IPaymentProcessor paymentProcessor,<br>        ILogger&lt;OrderService&gt; logger)<br>    {<br>        _repository = repository;<br>        _paymentProcessor = paymentProcessor;<br>        _logger = logger;<br>    }<br>    public async Task ProcessOrderAsync(Order order)<br>    {<br>        _logger.LogInformation(&quot;Processing order {OrderId}&quot;, order.Id);<br>        await _paymentProcessor.ProcessAsync(order.Amount);<br>        await _repository.SaveAsync(order);<br>    }<br>}<br>// 3. Controller receiving IOrderService<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class OrdersController : ControllerBase<br>{<br>    private readonly IOrderService _orderService;<br>    public OrdersController(IOrderService orderService)<br>    {<br>        _orderService = orderService;<br>    }<br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; CreateOrder([FromBody] Order order)<br>    {<br>        await _orderService.ProcessOrderAsync(order);<br>        return Ok();<br>    }<br>}<br>// 4. Register services<br>builder.Services.AddScoped&lt;IOrderService, OrderService&gt;();<br>builder.Services.AddScoped&lt;IOrderRepository, OrderRepository&gt;();<br>builder.Services.AddTransient&lt;IPaymentProcessor, PaymentProcessor&gt;();</pre><p>When a request requires OrdersController, the DI container resolves its dependencies recursively: OrdersController → OrderService → OrderRepository and PaymentProcessor, creating the required object graph according to the registered lifetimes.</p><p><strong>Summary</strong></p><p>Understanding how the .NET DI container resolves dependencies under the hood helps you design cleaner architectures and diagnose subtle runtime issues:</p><ul><li>Inversion of Control decouples classes from creating their own dependencies, improving testability and flexibility.</li><li>Constructor Injection provides an explicit, discoverable convention for expressing required dependencies.</li><li>The .NET DI container resolves the dependency graph, selects the constructor with the most resolvable parameters, creates the required objects according to their lifetimes, and manages disposal for services it creates.</li></ul><p>The important takeaway is that constructor injection isn’t magic. The DI container is solving an object-construction problem: determine what needs to be created, determine how those dependencies are constructed, select an appropriate constructor, manage lifetimes, and return the requested object.</p><p>Thank you and <strong>Happy Coding!</strong> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=333d34c11f24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey to Microsoft Certified DevOps Engineer Expert]]></title>
            <link>https://satyampushkar.medium.com/my-journey-to-microsoft-certified-devops-engineer-expert-2444a57de934?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/2444a57de934</guid>
            <category><![CDATA[az-204]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[az-400]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[microsoft-certification]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 17:22:30 GMT</pubDate>
            <atom:updated>2023-08-11T05:41:18.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*reOOSNLHARCfH1ksbGnRKg.png" /></figure><p>In today’s rapidly changing tech world, Cloud &amp; DevOps expertise has become essential for streamlined software delivery. One of the most recognized validations of these skillsets in the Microsoft universe are <a href="https://learn.microsoft.com/en-us/certifications/azure-developer/"><em>Microsoft Certified: Azure Developer Associate</em></a> &amp; <a href="https://learn.microsoft.com/en-us/certifications/devops-engineer/"><em>Microsoft Certified: DevOps Engineer Expert</em></a> certification. Allow me to share my journey of securing these certifications, along with strategies and courses that played a pivotal role.</p><h3>Exam details:</h3><ul><li><a href="https://learn.microsoft.com/en-us/certifications/exams/az-204/"><strong>Exam AZ-204: Developing Solutions for Microsoft Azure:</strong></a> This exam measures your ability to accomplish the following technical tasks: develop Azure compute solutions, develop for Azure storage, implement Azure security, monitor, troubleshoot, and optimize Azure solutions, and connect to and consume Azure services and third-party services. On successful completion of this exam you will get certified as <a href="https://learn.microsoft.com/en-us/certifications/azure-developer/"><strong><em>Microsoft Certified: Azure Developer Associate</em></strong></a><em>.</em></li><li><a href="https://learn.microsoft.com/en-us/certifications/exams/az-400/"><strong>Exam AZ-400: Designing and Implementing Microsoft DevOps Solutions:</strong></a> This exam measures your ability to accomplish the following technical tasks: configure processes and communications, design and implement source control, design and implement build and release pipelines, develop a security and compliance plan, and implement an instrumentation strategy. This exam has a prerequisite of completing the above mentioned exam <a href="https://learn.microsoft.com/en-us/certifications/exams/az-204/"><em>Exam AZ-204: Developing Solutions for Microsoft Azure</em></a> or <a href="https://learn.microsoft.com/en-us/certifications/exams/az-104/"><em>Exam AZ-104: Microsoft Azure Administrator</em></a>. On successful completion of this exam you will get certified as <a href="https://learn.microsoft.com/en-us/certifications/devops-engineer/"><strong><em>Microsoft Certified: DevOps Engineer Expert</em></strong></a><em>.</em></li></ul><p>I took the above 2 exams in the below mentioned order and on completion acquired my certification of Microsoft Certified: DevOps Engineer Expert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*64su9qthnEFdVuzAilLipQ.png" /><figcaption>from <a href="https://learn.microsoft.com/en-us/certifications/devops-engineer/">https://learn.microsoft.com/en-us/certifications/devops-engineer/</a></figcaption></figure><h3>My Journey/Strategy:</h3><ol><li><em>Know the Field</em>: Familiarize yourself with prerequisites for the certification exam which you want to appear for. This is very important. You need to clearly understand the different sections and their weightage. This will help you in preparation. You might get few topics which you don&#39;t known or haven&#39;t worked on earlier. Those will be new learnings for you.</li><li><em>Hands-On Experience</em>: I have worked on Azure in my professional work. That has really helped me a lot. But there were many things which were new to me. While doing preparation I learned a many new concepts and I feel that has made me a better developer.</li><li><em>Udemy Courses</em>: I went through 2 Udemy courses (mentioned below) which I highly recommend. These courses are good to start with and gave me a good insight on many different topics which are required for theses certifications in a short time (try 2x speed).</li><li><em>Utilize Microsoft Learn</em>: Microsoft has a very well curated platform called Microsoft learn. I highly recommend you to go through it for these certifications or any other Microsoft related learnings.</li><li><em>Familiarize yourself with official Microsoft Documentation</em>: Microsoft’s official documentation is a treasure trove — For each of the topic I went through that topic’s explanation in MS docs and it has literally everything what I wanted(and more; even beyond the scope of certification exam) .</li><li><em>Practice Exams</em>: To fine-tune my readiness, practice exams were indispensable. They gave me a clear understanding of question types, optimizing my approach. I took 2 practice sets which are mentioned below.</li></ol><p>I followed the above mentioned strategy in the exact order. I felt exam Az-204 to be a bit challenging as topics covered under it was very vast. And if you are really interested in what &amp; how of Azure or in general about cloud or tech, you will definitely fall of the track of exam course (for good reason only). It took me around 3 months of preparation to crack Az-204.</p><p>On the other hand, I found Az-400 to be relatively simple &amp; easy. It took me hardly a month to prepare.</p><h3>Recommended Courses:</h3><ol><li>Microsoft Learn: Free modules and learning paths cover <a href="https://learn.microsoft.com/en-us/certifications/exams/az-204/">https://learn.microsoft.com/en-us/certifications/exams/az-204/</a>.</li><li>Microsoft Learn: Free modules and learning paths cover <a href="https://learn.microsoft.com/en-us/certifications/exams/az-400/">Azure basics and advanced DevOps practices</a>.</li><li>Udemy — <a href="https://www.udemy.com/course/70532-azure/">AZ-204 Developing Solutions for Microsoft Azure</a></li><li>Udemy — <a href="https://www.udemy.com/course/azure100/">AZ-400 Designing and Implementing DevOps Certification 2022</a></li><li>Udemy Practice set — <a href="https://www.udemy.com/course/az-204-mock-test/">https://www.udemy.com/course/az-204-mock-test/</a>.</li><li>Udemy Practice set — <a href="https://www.udemy.com/course/az-400-mock-tests/">https://www.udemy.com/course/az-400-mock-tests/</a>.</li></ol><h3>Conclusion:</h3><p>Certification isn’t the sole measure of expertise, but rather a tool for enhancing and updating our skills. As I acquired these certifications, my confidence grew and my LinkedIn profile gained added weight. The journey was both a revisiting of my knowledge and a step toward greater mastery. I invite you to embark on your own journey of growth and skill enhancement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2444a57de934" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimal API in dotnet]]></title>
            <link>https://satyampushkar.medium.com/minimal-api-in-dotnet-33cf9c818c4a?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/33cf9c818c4a</guid>
            <category><![CDATA[minimal-api]]></category>
            <category><![CDATA[dotnet6]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 16:21:36 GMT</pubDate>
            <atom:updated>2022-04-20T16:21:36.433Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article showcases how simple it is for anyone to create a minimal API using dotnet 6.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*1KNChy9HDns5CvfC1lS6Xg.png" /></figure><p>Being a dotnet developer I always envied NodeJS developers that they can create API in a single file. On the other hand as a dotnet developer, you must had needed at least need 3 files: <em>startup.cs</em>, <em>programm.cs</em> and <em>one controller</em>. But that’s not the case anymore!! In November 2021 dotnet introduces Minimal API and now I can create an API with just one file in dotnet.</p><p>Minimal APIs are designed by dotnet team to create HTTP APIs with minimal dependencies. These are very apt for microservices and any other apps that want to have only the minimum files, features, and dependencies in ASP.NET Core.</p><p>Recently I was trying to understand different microservices architecture and stumbled upon minimal API and now I am absolutely in love with it. If you want to create a sample microservice for test or analysis purpose, you can spin up an API quickly with just one file. And why only for test or analysis only, you can create a full fledged enterprise grade APIs/applications using Minimal APIs. And talking about performance it is faster than the controller based approach, (to know more please read this <a href="https://benfoster.io/blog/minimal-apis-why-should-you-care/">article</a>).</p><h4>Benefits of Minimal API</h4><ul><li>Reduced complexity</li><li>Easy to get started. <em>You can run an API with just 3 lines of code</em>.</li><li>Increased performance. <em>Microsoft has done a lot of bootstrapping to make application compile, build and run faster</em>.</li></ul><h4>Create Minimal API with Command Line</h4><p>Run the following command to create a Minimal API.</p><pre><strong>dotnet new web -o MinAPIfrmCmdLine</strong></pre><p>This will create an API under the folder ‘<em>MinAPIfrmCmdLine</em>’. Here if you check the folder, you will find there are only 2 important files here: <em>Program.cs</em> and <em>.csproj</em> file. And if you check the content of <em>Program.cs</em>, you will find there are only 4 lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*DIy7SvCecoqKKRdX8vCouQ.png" /></figure><p>Once you run the app, you will find that the app is running and listening to localhost. You can see that how easy it has become now to create and run an API in dotnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*di61sYJpZ-Tjq3lr6CUBPA.png" /></figure><h4>Create Minimal API with Visual Studio</h4><p>In Visual Studio 2022, select the option to create a new project. Choose the template “ASP .NET Core Web API”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Z-IK2jNWbqrev3zvVjTInw.png" /></figure><p>After that you will be asked to provide the <em>Project Name</em>, <em>Location</em> to save and <em>Solution Name</em>. Please enter it appropriately. On next screen, you will find the option to fill the following information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*nFUUdXX-LcTipqFz3uM5HQ.png" /></figure><p>You can choose based on your choice. But please make sure to uncheck the option “<em>Use Controller</em>” to create a Minimal API.</p><p>That’s it!! Once you click on <em>Create </em>button, your API(Minimal API), without controllers!! In a single file!! is ready.</p><p>The template provided by Microsoft creates an API to show weather forecast. You can see how the swagger page and console are created denoting the API is ready to serve requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiGKRQNixPwK5mwfmnun8Q.png" /></figure><p><em>This was a sample demo showing how to create Minimal API in dotnet. Hope you found this article useful.</em></p><p><em>For further reading on </em><strong><em>Minimal API </em></strong><em>you can check out these </em><strong><em>Microsoft docs</em></strong><em>:</em></p><ol><li><a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0&amp;tabs=visual-studio"><strong><em>Create a minimal web API with ASP.NET Core</em></strong></a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0"><strong><em>Minimal APIs overview</em></strong></a></li></ol><p><em>Please do checkout other articles by me and share your feedback(s) if any. Thank you and Happy Coding :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33cf9c818c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outbox Pattern using dotnet 6]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/c-sharp-programming/outbox-pattern-using-dotnet-6-41adab98974b?source=rss-1a12c14f5892------2"><img src="https://cdn-images-1.medium.com/max/771/1*lHqSp4SIkhXaBMR25owUyQ.jpeg" width="771"></a></p><p class="medium-feed-snippet">This article showcases how to implement the Transactional Outbox pattern in microservices architecture with sample dotnet code. You can&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/c-sharp-programming/outbox-pattern-using-dotnet-6-41adab98974b?source=rss-1a12c14f5892------2">Continue reading on Any Programming »</a></p></div>]]></description>
            <link>https://medium.com/c-sharp-programming/outbox-pattern-using-dotnet-6-41adab98974b?source=rss-1a12c14f5892------2</link>
            <guid isPermaLink="false">https://medium.com/p/41adab98974b</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[dotnet6]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[transactional-outbox]]></category>
            <dc:creator><![CDATA[Satyam Pushkar]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 03:37:40 GMT</pubDate>
            <atom:updated>2026-04-11T21:04:56.357Z</atom:updated>
        </item>
    </channel>
</rss>