<?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 Pramudi Srimali on Medium]]></title>
        <description><![CDATA[Stories by Pramudi Srimali on Medium]]></description>
        <link>https://medium.com/@sripramudi95?source=rss-4697cde28666------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lna50EBDXCIm2ajHG2Jxag.png</url>
            <title>Stories by Pramudi Srimali on Medium</title>
            <link>https://medium.com/@sripramudi95?source=rss-4697cde28666------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:07:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sripramudi95/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[Understanding Dependency Injection in ASP.NET Core: A Beginner’s Guide]]></title>
            <link>https://medium.com/@sripramudi95/understanding-dependency-injection-in-asp-net-core-a-beginners-guide-9007b406f887?source=rss-4697cde28666------2</link>
            <guid isPermaLink="false">https://medium.com/p/9007b406f887</guid>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[asp-dot-net-developer]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Pramudi Srimali]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 16:42:51 GMT</pubDate>
            <atom:updated>2026-06-26T16:42:51.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXA5Gh7iMUgZ9gwv7glQsQ.png" /></figure><p>When I first started learning ASP.NET Core, one concept that seemed confusing was <strong>Dependency Injection (DI)</strong>.</p><p>Questions like these often came to mind:</p><ul><li>Why does a class need another object?</li><li>Why shouldn’t a class create its own objects?</li><li>What exactly is “tight coupling”?</li><li>Why is Dependency Injection considered such an important feature in ASP.NET Core?</li></ul><p>If you’ve had similar questions, this article is for you.</p><p>Let’s understand Dependency Injection from the very beginning</p><h3>What is Dependency Injection?</h3><p>Dependency Injection (DI) is a design pattern in which a class receives the objects it needs from an external source instead of creating them itself.</p><p>In simple words,</p><blockquote><strong><em>Don’t create what you need. Ask for it, and let someone else provide it.</em></strong></blockquote><p>ASP.NET Core has a built-in Dependency Injection container that automatically creates and provides these objects whenever they are needed.</p><h3>What is a Dependency?</h3><p>A dependency is simply <strong>something that another class needs to perform its job</strong>.</p><p>Imagine you have a class responsible for managing products.</p><pre>public class ProductService<br>{<br>    private MyDbContext _context;<br>}</pre><p>Here, ProductService needs MyDbContext to communicate with the database.</p><p>Therefore,</p><p><strong>MyDbContext is a dependency of ProductService.</strong></p><p>Without the database context, ProductService cannot retrieve, insert, update, or delete products.</p><h3>Why Does a Class Need Another Object?</h3><p>Every class should have <strong>one primary responsibility</strong>.</p><p>For example:</p><ul><li>ProductService handles business logic.</li><li>MyDbContext handles database operations.</li><li>EmailService sends emails.</li><li>LoggerService records logs.</li></ul><p>Instead of one class trying to perform every task, each class focuses on a single responsibility and collaborates with other classes.</p><p>This makes applications easier to understand and maintain.</p><h3>A Real-Life Example</h3><p>Imagine a restaurant.</p><p>The restaurant manager can:</p><ul><li>Take customer orders</li><li>Manage employees</li><li>Handle payments</li></ul><p>But the manager doesn’t cook the food.</p><p>For cooking, the manager depends on a chef.</p><pre>Restaurant Manager<br>        │<br>        ▼<br>      Chef</pre><p>Similarly,</p><pre>ProductService<br>        │<br>        ▼<br>   MyDbContext</pre><p>The manager depends on the chef.</p><p>The service depends on the database context.</p><p>That required object is called a <strong>dependency</strong>.</p><h3>What Happens Without Dependency Injection?</h3><p>Many beginners write code like this:</p><pre>public class ProductService<br>{<br>    private MyDbContext _context;<br><br>public ProductService()<br>    {<br>        _context = new MyDbContext();<br>    }<br>}</pre><p>At first glance, this seems perfectly fine.</p><p>The class simply creates the object it needs.</p><p>But this approach creates several problems.</p><h3>Problem 1: Tight Coupling</h3><p>In this example, ProductService directly creates MyDbContext.</p><p>This means the two classes are strongly connected.</p><pre>ProductService<br>      │<br>      ▼<br> MyDbContext</pre><p>This relationship is called <strong>tight coupling</strong>.</p><p>If MyDbContext changes significantly, ProductService may also need to change.</p><p>The more tightly connected classes become, the harder the application is to maintain.</p><h3>Problem 2: Difficult to Replace Dependencies</h3><p>Suppose your application initially uses SQL Server.</p><p>Later, your company decides to migrate to another database.</p><p>Since the object is created directly inside the class,</p><pre>_context = new MyDbContext();</pre><p>you now need to modify the class itself.</p><p>If hundreds of classes create MyDbContext this way, you&#39;ll have to update all of them.</p><p>That’s a lot of unnecessary work.</p><h3>Problem 3: Hard to Test</h3><p>Testing becomes much more difficult.</p><p>Imagine writing a unit test for ProductService.</p><p>If it always creates a real database connection,</p><pre>new MyDbContext()</pre><p>your tests may:</p><ul><li>Connect to a real database</li><li>Require test data</li><li>Run slowly</li><li>Fail because of database issues</li></ul><p>Instead, it’s much better if the service can receive a fake or mock database object during testing.</p><h3>Problem 4: Repeated Object Creation</h3><p>Suppose three different controllers need a database context.</p><p>Without Dependency Injection:</p><pre>ProductController<br>      │<br> new MyDbContext()<br><br><br>OrderController<br>      │<br> new MyDbContext()<br><br><br>CustomerController<br>      │<br> new MyDbContext()</pre><p>Each controller creates its own database context.</p><p>Managing all these objects becomes difficult as the application grows.</p><h3>How Dependency Injection Solves These Problems</h3><p>Instead of creating the object inside the class,</p><pre>_context = new MyDbContext();</pre><p>we receive it through the constructor.</p><pre>public class ProductService<br>{<br>    private readonly MyDbContext _context;<br><br>public ProductService(MyDbContext context)<br>    {<br>        _context = context;<br>    }<br>}</pre><p>Notice that there is no new MyDbContext().</p><p>The service simply says,</p><blockquote><em>“I need a MyDbContext.”</em></blockquote><p>It doesn’t care who creates it.</p><p>ASP.NET Core takes care of that.</p><h3>Registering Services in ASP.NET Core</h3><p>Before ASP.NET Core can provide an object, it must know how to create it.</p><p>That’s why we register services.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContext&lt;MyDbContext&gt;(options =&gt;<br>    options.UseSqlServer(<br>        builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));</pre><p>Let’s understand this code.</p><h3>Step 1: Create the Builder</h3><pre>var builder = WebApplication.CreateBuilder(args);</pre><p>The builder is responsible for configuring the application.</p><h3>Step 2: Access the Service Container</h3><pre>builder.Services</pre><p>This represents the built-in Dependency Injection container.</p><p>It stores all the services your application needs.</p><h3>Step 3: Register the Database Context</h3><pre>builder.Services.AddDbContext&lt;MyDbContext&gt;();</pre><p>This tells ASP.NET Core:</p><blockquote><em>“Whenever someone asks for MyDbContext, create it and provide it automatically.”</em></blockquote><h3>Step 4: Configure SQL Server</h3><pre>options.UseSqlServer(...)</pre><p>This specifies that Entity Framework Core should use SQL Server as the database provider.</p><h3>Step 5: Read the Connection String</h3><pre>builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)</pre><p>This reads the database connection details from appsettings.json.</p><p>Example:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=.;Database=ShopDB;Trusted_Connection=True;&quot;<br>  }<br>}</pre><h3>What Happens Behind the Scenes?</h3><p>Suppose a controller needs MyDbContext.</p><pre>public class ProductController : Controller<br>{<br>    private readonly MyDbContext _context;<br><br>public ProductController(MyDbContext context)<br>    {<br>        _context = context;<br>    }<br>}</pre><p>When ASP.NET Core creates ProductController, it notices that the constructor requires MyDbContext.</p><p>It checks the Dependency Injection container.</p><p>Since MyDbContext was registered earlier, ASP.NET Core creates the object and injects it into the controller automatically.</p><p>You never have to write:</p><pre>new MyDbContext();</pre><p>This automatic process is called <strong>Dependency Injection</strong>.</p><h3>Tight Coupling vs Loose Coupling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zeDqJGIbycYGkqbjcwPucg.png" /><figcaption>Tight coupling vs loose coupling comparison</figcaption></figure><p>Dependency Injection helps achieve <strong>loose coupling</strong>, making applications cleaner, easier to maintain, and easier to test.</p><h3>Key Benefits of Dependency Injection</h3><ul><li>Cleaner code</li><li>Better separation of responsibilities</li><li>Easier testing</li><li>Reduced coupling</li><li>Easier maintenance</li><li>More reusable services</li><li>Built-in support in ASP.NET Core</li></ul><h3>Final Thoughts</h3><p>Dependency Injection is much more than a framework feature — it is a design principle that encourages writing clean, maintainable, and scalable applications.</p><p>Instead of allowing every class to create its own dependencies, ASP.NET Core provides those dependencies through its built-in Dependency Injection container.</p><p>As your applications grow, you’ll appreciate how DI reduces complexity, improves testability, and makes your codebase easier to evolve.</p><p>If you’re learning ASP.NET Core, mastering Dependency Injection is one of the best investments you can make. Once you understand this concept, many other ASP.NET Core features become much easier to grasp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9007b406f887" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>