{"id":13930,"date":"2023-10-12T08:52:52","date_gmt":"2023-10-12T08:52:52","guid":{"rendered":"https:\/\/positiwise.com\/blog\/?p=13930"},"modified":"2023-12-27T08:50:19","modified_gmt":"2023-12-27T08:50:19","slug":"dependency-injection-in-net-core-with-example","status":"publish","type":"post","link":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example","title":{"rendered":"What is Dependency Injection in .NET Core? &#8211; Explained with Code Examples"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong class=\"pw-highlight-text-color\"><em>Quick Overview:<\/em><\/strong><br>The blog introduces dependency injection in .NET Core, its advantages, and the need to implement it. Further, it provides exposure to the procedure of configuring it in an ASP.NET Core application to separate the dependencies between classes. In addition, you can also avail of the details of manual method and action method injection with complete outputs.<\/p><div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#A_Run-Through_NET_Core_vs_Nodejs\" >A Run-Through: .NET Core vs Node.js<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#NET_Core\" >.NET Core<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Pros_of_using_NET_Core\" >Pros of using .NET Core<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Nodejs\" >Node.js<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#A_Deep_Dive_into_NET_Core_vs_Nodejs\" >A Deep Dive into .NET Core vs. Node.js<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Processing_Approach_and_Performance\" >Processing Approach and Performance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Security\" >Security<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Scalability\" >Scalability<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Platform_Adaptability\" >Platform Adaptability<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Support_from_Community\" >Support from Community<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Comparison_Table_between_NET_Core_and_Nodejs\" >Comparison Table between .NET Core and Node.js<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\/#Wrapping_Up_on_NET_Core_vs_Nodejs\" >Wrapping Up on .NET Core vs Node.js<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">With the frequently changing user requirements, it\u2019s not recommended to implement dependency between classes. It causes additional time and effort to implement the changes and make all modifications within a minimal time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To resolve this issue, dependency injection in .NET Core applications is used. It aids in separating the dependencies and make application coupled loosely. It&#8217;s a must-have skill for <a href=\"https:\/\/positiwise.com\/hire-asp-net-developers\">.NET developers<\/a>, and you should also learn it via this blog. Here, you will understand what Dependency injection is and how to implement the common type of dependency injection.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Dependency Injection?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dependency Injection is a <a href=\"https:\/\/positiwise.com\/services\/custom-software-development\">software development<\/a> and design pattern that helps in eliminating the dependency of one class on the other class. Using dependency injection or DI primarily aims to build loosely coupled applications instead of tightly coupled ones.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The following are the top advantages of using dependency injection in .NET Core web API and applications:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Reusability<\/strong>: Dependency injection enables developers to reuse a code block, as they can share dependencies between classes.<\/li>\n\n\n\n<li><strong>Easy Testing<\/strong>: During <a href=\"https:\/\/positiwise.com\/blog\/unit-testing-in-net-core-using-nunit\">unit testing<\/a> procedures, dependency injection enables the developers to use mock objects for testing the application. It provides accurate results, leading to patching loopholes, fixing errors, and streamlining code maintenance in .NET Core.<\/li>\n\n\n\n<li><strong>Loose Coupling<\/strong>: DI helps to remove the dependency of one class over another class. This will result in accurate output even if you modify a single class, and it will not impact the dependent class.<\/li>\n\n\n\n<li><strong>Extensibility<\/strong>: With the use of dependency injection, the application becomes more flexible and scalable, allowing it to remove dependencies while retaining uptime.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">The Need for Dependency Injection in .NET Core<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s see an example below to understand the need for dependency injection.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Car\n{\n    private AUDI _audi;\n    public Car()\n    {\n        _audi = new AUDI();\n    }\n}\npublic class AUDI\n{\n    public AUDI()\n    {\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the above code, two classes are present: class Car and class AUDI. The class Car depends on class AUDI for providing the output. Therefore, both these classes are tightly coupled, and due to this, each time the program runs, an AUDI class object needs to be created.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, suppose that you add a ModelName parameter in the AUDI class constructor. Then, you need to add and pass the same parameter in the Car class, similar to the following code example. Otherwise, your program will not provide the output, which is, in our case, the model name.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Car\n{\n    private AUDI _audi;\n    public Car()\n    {\n        _audi = new AUDI(\"BMW A7\");\n    }\n}\npublic class AUDI\n{\n    public AUDI(string ModelName)\n    {\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Due to the tight coupling of these classes, modification made in one class impacts the other. It&#8217;s not a good practice for large projects, as it&#8217;s a time, cost, and effort-consuming task. Thus, you need dependency injection to break hard coupling and make your .NET application loosely coupled.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Dependency Injection Code Example: A Deep Insight Into DI Implementation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To understand the use of dependency injection, we are going to create an ASP.NET Core project using the Visual Studio IDE. Learning the dependency injection implementation doesn&#8217;t make any significant difference in ASP.NET Core, as it is based on <a href=\"https:\/\/positiwise.com\/hire\/asp-net-core-development-company\">.NET Core development<\/a> technology.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But, before you start with the code examples, ensure that you understand object-oriented programming, C# programming language, and ASP.NET Core.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s start with an example, divided into different steps.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step #1:<\/strong> Download and install the 2019 or above version of the <strong><em>Visual Studio IDE<\/em><\/strong> on your machine.<\/li>\n\n\n\n<li><strong>Step #2:<\/strong> Open the <strong><em>VS IDE<\/em><\/strong> and create a <strong><em>new project<\/em><\/strong>.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1010\" height=\"541\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/create-new-project-vs-ide.png\" alt=\"create new project vs ide\" class=\"wp-image-13943\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/create-new-project-vs-ide.png 1010w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/create-new-project-vs-ide-300x161.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/create-new-project-vs-ide-768x411.png 768w\" sizes=\"auto, (max-width: 1010px) 100vw, 1010px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step #3:<\/strong> On the &#8220;<strong><em>Create a new project<\/em><\/strong>&#8221; window, choose the ASP.NET Core empty template and then left-click on the <strong><em>Next<\/em><\/strong> button.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"997\" height=\"535\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/select-asp-net-core-empty.png\" alt=\"select asp net core empty\" class=\"wp-image-13945\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/select-asp-net-core-empty.png 997w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/select-asp-net-core-empty-300x161.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/select-asp-net-core-empty-768x412.png 768w\" sizes=\"auto, (max-width: 997px) 100vw, 997px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step #4:<\/strong> You will see a new project creation window asking you to provide project details, such as its name, solution name, and storage location. Define all the parameters per your needs and again hit the Next button. For this tutorial, we are using the project and solution name &#8220;<strong><em>FirstCoreMVCWebApplication.<\/em><\/strong>\u201d<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1106\" height=\"523\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/configure-new-project-net-core.png\" alt=\"configure new project net core\" class=\"wp-image-13942\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/configure-new-project-net-core.png 1106w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/configure-new-project-net-core-300x142.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/configure-new-project-net-core-1024x484.png 1024w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/configure-new-project-net-core-768x363.png 768w\" sizes=\"auto, (max-width: 1106px) 100vw, 1106px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 5:<\/strong> At this step, provide the additional details, including the .NET framework <strong><em>version<\/em><\/strong>, configuration of <strong><em>HTTPS<\/em><\/strong>, enabling <strong><em>docker<\/em><\/strong>, and usage of <strong><em>top-level statements<\/em><\/strong>.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1109\" height=\"442\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/additional-information-net-core-empty.png\" alt=\"additional information net core empty\" class=\"wp-image-13941\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/additional-information-net-core-empty.png 1109w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/additional-information-net-core-empty-300x120.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/additional-information-net-core-empty-1024x408.png 1024w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/additional-information-net-core-empty-768x306.png 768w\" sizes=\"auto, (max-width: 1109px) 100vw, 1109px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 6:<\/strong> Hit the <strong><em>Create<\/em><\/strong> button, and your ASP.NET Core project will be created and displayed. Further, see the Solutions Explorer window on the right side. You will see a project structure similar to the below snippet.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"325\" height=\"177\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/firstcoremvcwebapplication-project.png\" alt=\"firstcoremvcwebapplication project\" class=\"wp-image-13944\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/firstcoremvcwebapplication-project.png 325w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/firstcoremvcwebapplication-project-300x163.png 300w\" sizes=\"auto, (max-width: 325px) 100vw, 325px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 7:<\/strong> Now, we will add the models to our empty ASP.NET Core project.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You are required to create a new folder named &#8220;<strong><em>Models<\/em><\/strong>&#8221; and then create a class file named &#8220;<strong><em>Student.cs<\/em><\/strong>&#8221; under it. This Student.cs file will be the first model of our project. So, open it and put the below code in the file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace FirstCoreMVCWebApplication.Models\n{\n    public class Student\n    {\n        public int StudentId { get; set; }\n        public string? Name { get; set; }\n        public string? Branch { get; set; }\n        public string? Section { get; set; }\n        public string? Gender { get; set; }\n    }\n}<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 8:<\/strong> This step is about building a service interface.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Under the same model folder created in step 7, add a new file named \u201c<strong><em>IStudetnRepository.cs.<\/em><\/strong>\u201d Open the newly created file and copy the below-provided code to it. The code will be used to define the operations that can be executed on student data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System.Collections.Generic;\nnamespace FirstCoreMVCWebApplication.Models\n{\n    public interface IStudentRepository\n    {\n        Student GetStudentById(int StudentId);\n        List&lt;Student&gt; GetAllStudent();\n    }\n}<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 9:<\/strong> Here, we will be developing the service implementation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Again, create a new class file in the same Model folder named &#8220;<strong><em>StudentRepository.cs.<\/em><\/strong>\u201d Till now, we have created a total of three class files in the Model folder.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The StudentRepository.cs file will implement both interfaces in the IStudetnRepository.cs file. To finalize this implementation, you should put the code below in the StudentRepository.cs file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System.Collections.Generic;\nusing System.Linq;\n\nnamespace FirstCoreMVCWebApplication.Models\n{\n    public class StudentRepository : IStudentRepository\n    {\n        public List&lt;Student&gt; DataSource()\n        {\n            return new List&lt;Student&gt;()\n            {\n                new Student() { StudentId = 201, Name = \"Adam\", Branch = \"CSE\", Section = \"A\", Gender = \"Male\" },\n                new Student() { StudentId = 202, Name = \"Aeron\", Branch = \"ETC\", Section = \"B\", Gender = \"Male\" },\n                new Student() { StudentId = 203, Name = \"Rahul\", Branch = \"CSE\", Section = \"A\", Gender = \"Male\" },\n                new Student() { StudentId = 204, Name = \"Pamela\", Branch = \"CSE\", Section = \"A\", Gender = \"Female\" },\n                new Student() { StudentId = 205, Name = \"Sam\", Branch = \"ETC\", Section = \"B\", Gender = \"Female\" }\n            };\n        }\n\n        public Student GetStudentById(int StudentId)\n        {\n            return DataSource().FirstOrDefault(e =&gt; e.StudentId == StudentId) ?? new Student();\n        }\n\n        public List&lt;Student&gt; GetAllStudent()\n        {\n            return DataSource();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In addition, in this code example, student data is hard-coded. But, you can utilize a database of your choice while developing a real-time application. Even when a business opts for .NET Core development services, real-time data is used only.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 10:<\/strong> From the solutions explorer, open the <strong><em>Program.cs<\/em><\/strong> file and copy the below-provided code into it.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace FirstCoreMVCWebApplication\n{\n    public class Program\n    {\n        public static void Main(string&#91;] args)\n        {\n            var builder = WebApplication.CreateBuilder(args);\n\n            \/\/ Add MVC services to the container.\n            builder.Services.AddMvc();\n\n            var app = builder.Build();\n\n            app.UseRouting();\n            app.UseEndpoints(endpoints =&gt;\n            {\n                \/\/Configuring the MVC middleware to the request processing pipeline\n                endpoints.MapDefaultControllerRoute();\n            });\n\n            app.Run();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This code block will support the configuration of the IoC container and MVC service along with the required middleware. All these components will work collaboratively to process data in the pipeline. Save the code in the Program.cs file and move further.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 11:<\/strong> Now, you should create another folder named <strong><em>Controllers<\/em><\/strong>. Under this folder, create a class file and name it <strong><em>HomeController.cs<\/em><\/strong>. In this class file, you should put the following code and save it.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>using FirstCoreMVCWebApplication.Models;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\n\nnamespace FirstCoreMVCWebApplication.Controllers\n{\n    public class HomeController : Controller\n    {\n        public JsonResult Index()\n        {\n            StudentRepository repository = new StudentRepository();\n            List&lt;Student&gt; allStudentDetails = repository.GetAllStudent();\n            return Json(allStudentDetails);\n        }\n\n        public JsonResult GetStudentDetails(int Id)\n        {\n            StudentRepository repository = new StudentRepository();\n            Student studentDetails = repository.GetStudentById(Id);\n            return Json(studentDetails);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Currently, we have not configured dependency injection. It will get configured in further steps. But, before that, you should analyze the output without the use of dependency injection. As a result, when you run the application with dependency injection, you will get to know how DI makes a difference.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 12:<\/strong> <strong><em>Run the application<\/em><\/strong> without dependency injection. You will see an output similar to the following snippet.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"900\" height=\"600\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection.png\" alt=\"without dependency injection\" class=\"wp-image-13951\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection.png 900w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection-300x200.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection-768x512.png 768w\" sizes=\"auto, (max-width: 900px) 100vw, 900px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So, here\u2019s the output of our application running without dependency injection. And yes, there\u2019s a problem that you must avoid for medium and large projects with dynamic requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Problem Description:<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The HomeController.cs file depends on the StudentRepository.cs class file. The StudentRepository.cs class instance calls the GetStudentById() method because of it. Therefore, both classes are tightly coupled.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you change the name of StudentRepository.cs or modify it, you have to modify it for HomeController.cs manually. If you have a large application with hard coupling, then it will take a lot of time, resources, and time, and if you utilize dependency injection, it will eliminate this problem.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They will add the object of the class on which the other class depends to their code with the help of DI. So, whatever changes you make will not impact the functioning, and all the classes will invoke methods as before. Thus, the application will become loosely coupled.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, let\u2019s implement the dependency injection (DI). You should always <a href=\"https:\/\/positiwise.com\/hire\/hire-dot-net-core-developers\">hire .NET Core developers<\/a> for this implementation to avoid misconfigurations and errors.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 13:<\/strong> <strong><em>Open the Program.cs<\/em><\/strong> file and add the below code to its main method. Rest, the type of service you can select according to requirements.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>using FirstCoreMVCWebApplication.Models;\n\nnamespace FirstCoreMVCWebApplication\n{\n    public class Program\n    {\n        public static void Main(string&#91;] args)\n        {\n            var builder = WebApplication.CreateBuilder(args);\n\n            \/\/ Add Framework MVC services to the Container.\n            builder.Services.AddMvc();\n\n            \/\/Application Service\n            builder.Services.AddSingleton&lt;IStudentRepository, StudentRepository&gt;();\n            \/\/builder.Services.AddSingleton(typeof(IStudentRepository), typeof(StudentRepository));\n            \/\/builder.Services.AddTransient&lt;IStudentRepository, StudentRepository&gt;();\n            \/\/builder.Services.AddTransient(typeof(IStudentRepository), typeof(StudentRepository));\n            \/\/builder.Services.AddScoped&lt;IStudentRepository, StudentRepository&gt;();\n            \/\/builder.Services.AddScoped(typeof(IStudentRepository), typeof(StudentRepository));\n\n            \/\/Add Application Service to the Container.\n            \/\/builder.Services.Add(new ServiceDescriptor(typeof(IStudentRepository),\n            \/\/    new StudentRepository())); \/\/ by default singleton\n            \/\/builder.Services.Add(new ServiceDescriptor(typeof(IStudentRepository),\n            \/\/    typeof(StudentRepository), ServiceLifetime.Singleton)); \/\/ singleton\n            \/\/builder.Services.Add(new ServiceDescriptor(typeof(IStudentRepository),\n            \/\/    typeof(StudentRepository), ServiceLifetime.Transient)); \/\/ Transient\n            \/\/builder.Services.Add(new ServiceDescriptor(typeof(IStudentRepository),\n            \/\/    typeof(StudentRepository), ServiceLifetime.Scoped));    \/\/ Scoped\n\n            var app = builder.Build();\n\n            app.UseRouting();\n            app.UseEndpoints(endpoints =&gt;\n            {\n                \/\/Configuring the MVC middleware to the request processing pipeline\n                endpoints.MapDefaultControllerRoute();\n            });\n\n            app.Run();\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 14:<\/strong> Go to the <strong><em>Models<\/em><\/strong> folder and open the <strong><em>HomeController.cs<\/em><\/strong> file to add the following code block. It will enable the IoC container to execute constructor injection.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>using FirstCoreMVCWebApplication.Models;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\n\nnamespace FirstCoreMVCWebApplication.Controllers\n{\n    public class HomeController : Controller\n    {\n        \/\/Create a reference variable of IStudentRepository\n        private readonly IStudentRepository? _repository = null;\n\n        \/\/Initialize the variable through constructor\n        public HomeController(IStudentRepository repository)\n        {\n            _repository = repository;\n        }\n\n        public JsonResult Index()\n        {\n            List&lt;Student&gt;? allStudentDetails = _repository?.GetAllStudent();\n            return Json(allStudentDetails);\n        }\n\n        public JsonResult GetStudentDetails(int Id)\n        {\n            Student? studentDetails = _repository?.GetStudentById(Id);\n            return Json(studentDetails);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 15:<\/strong> Once again, <strong><em>run the application<\/em><\/strong> to view the following output.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"900\" height=\"600\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection.png\" alt=\"without dependency injection\" class=\"wp-image-13951\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection.png 900w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection-300x200.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/without-dependency-injection-768x512.png 768w\" sizes=\"auto, (max-width: 900px) 100vw, 900px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">With the help of code modifications performed in steps 13 and 14, the IoC container is automatically passing StudentRepository.cs file instance to HomeController.cs. The constructor injects the object, a process known as constructor dependency injection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are many other injections that you can use, such as action method and property dependence. In addition, you can also avail of service manually per your needs. Built-in IoC containers do not support property dependence. To utilize it, a third-party container is necessary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To understand the two, let\u2019s have a look at them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. Action Method Dependency Injection<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For using the dependency injection in a single action method, you have to use the <strong><em>[Form Services]<\/em><\/strong> attribute. For this, you have to change the code in the HomeController.cs file, available in the Model folder.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go to the HomeController.cs file and modify the code with the following. Consequently, the dependency object will be injected into the reference variable of the IStudentRepository.cs file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using FirstCoreMVCWebApplication.Models;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\n\nnamespace FirstCoreMVCWebApplication.Controllers\n{\n    public class HomeController : Controller\n    {\n        public JsonResult Index(&#91;FromServices] IStudentRepository repository)\n        {\n            List&lt;Student&gt; allStudentDetails = repository.GetAllStudent();\n            return Json(allStudentDetails);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong><em>Output:<\/em><\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"900\" height=\"300\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/action-method-dependency-injection.png\" alt=\"action method dependency injection\" class=\"wp-image-13953\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/action-method-dependency-injection.png 900w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/action-method-dependency-injection-300x100.png 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/action-method-dependency-injection-768x256.png 768w\" sizes=\"auto, (max-width: 900px) 100vw, 900px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Manual Configuration<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As the name defines, it&#8217;s a manual configuration and doesn&#8217;t require any dependency services. Here, the application will be using the <strong><em>HttpContext property \u2013 RequestServices<\/em><\/strong>. For this configuration, again modify the HomeController.cs file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using FirstCoreMVCWebApplication.Models;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Collections.Generic;\n\nnamespace FirstCoreMVCWebApplication.Controllers\n{\n    public class HomeController : Controller\n    {\n        public JsonResult Index()\n        {\n            var services = this.HttpContext.RequestServices;\n           \n            IStudentRepository? _repository = (IStudentRepository?)services.GetService(typeof(IStudentRepository));\n            List&lt;Student&gt;? allStudentDetails = _repository?.GetAllStudent();\n            return Json(allStudentDetails);\n        }\n\n        public JsonResult GetStudentDetails(int Id)\n        {\n            var services = this.HttpContext.RequestServices;\n            IStudentRepository? _repository = (IStudentRepository?)services.GetService(typeof(IStudentRepository));\n            Student? studentDetails = _repository?.GetStudentById(Id);\n            return Json(studentDetails);\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Further, run the application to see the same output as above.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dependency injection is the need of new-age applications, as stakeholder requirements change dynamically. With the aid of DI, developers can create loosely coupled software, leading to removing dependency among classes. As a result, you save time and effort because all the changes get processed automatically without manually configuring the objects and instances.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To configure dependency injection in your .NET Core application, you can use the constructor injection method provided in this blog. In addition, you can also use the action method injection. From an expert&#8217;s perspective, one must utilize constructor injection. It will streamline the processes and help you remove class dependency in a better way.<\/p>\n  <div class=\"related-post slider\">\r\n        <div class=\"headline\">Related Posts<\/div>\r\n    <div class=\"post-list owl-carousel\">\r\n\r\n            <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-java-technology\">\r\n\r\n      <img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"800\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1.jpg 1200w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-300x200.jpg 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-1024x683.jpg 1024w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-768x512.jpg 768w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-java-technology\">\r\n        .Net Core vs. Java \u2013 Which One You Should Use for Your Projects?  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Precise Road Map for ASP.NET Developers\" href=\"https:\/\/positiwise.com\/blog\/roadmap-for-asp-dot-net-developers\">\r\n\r\n      <img loading=\"lazy\" decoding=\"async\" width=\"1021\" height=\"621\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\"Hire ASP.NET Developers - A Precise Road Map to Employ ASP.NET Developers\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1.jpg 1021w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1-300x182.jpg 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1-768x467.jpg 768w\" sizes=\"auto, (max-width: 1021px) 100vw, 1021px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Precise Road Map for ASP.NET Developers\" href=\"https:\/\/positiwise.com\/blog\/roadmap-for-asp-dot-net-developers\">\r\n        Precise Road Map for ASP.NET Developers  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\".NET Core vs Node.js: The Difference Explained by Web Expert\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\">\r\n\r\n      <img loading=\"lazy\" decoding=\"async\" width=\"1021\" height=\"621\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/NET-Core-VS-Node-js-jpg.webp\" class=\"attachment-full size-full wp-post-image\" alt=\"NET-Core-VS-Node-js\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/NET-Core-VS-Node-js-jpg.webp 1021w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/NET-Core-VS-Node-js-300x182.webp 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/NET-Core-VS-Node-js-768x467.webp 768w\" sizes=\"auto, (max-width: 1021px) 100vw, 1021px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\".NET Core vs Node.js: The Difference Explained by Web Expert\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-node-js\">\r\n        .NET Core vs Node.js: The Difference Explained by Web Expert  <\/a>\r\n\r\n        <\/div>\r\n      \r\n  <\/div>\r\n\r\n  <script>\r\n      <\/script>\r\n  <style>\r\n    .related-post {}\r\n\r\n    .related-post .post-list {\r\n      text-align: left;\r\n          }\r\n\r\n    .related-post .post-list .item {\r\n      margin: 5px;\r\n      padding: 0px;\r\n          }\r\n\r\n    .related-post .headline {\r\n      font-size: 2rem !important;\r\n      color: #212529 !important;\r\n          }\r\n\r\n    .related-post .headline {\r\nmargin-top: 0;\r\npadding-left: 1%;\r\n}.related-post .post-list .item .post_thumb {\r\n      max-height: 220px;\r\n      margin: 0px 0px 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n          }\r\n\r\n    .related-post .post-list .item .post_title {\r\n      font-size: 1rem;\r\n      color: #212529;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .post-list .item .post_excerpt {\r\n      font-size: 13px;\r\n      color: #3f3f3f;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .owl-dots .owl-dot {\r\n          }\r\n\r\n      <\/style>\r\n      <script>\r\n      jQuery(document).ready(function($) {\r\n        $(\".related-post .post-list\").owlCarousel({\r\n          items: 3,\r\n          responsiveClass: true,\r\n          responsive: {\r\n            0: {\r\n              items: 1,\r\n            },\r\n            768: {\r\n              items: 2,\r\n            },\r\n            1200: {\r\n              items: 3,\r\n            }\r\n          },\r\n                      rewind: true,\r\n                                loop: true,\r\n                                center: true,\r\n                                autoplay: true,\r\n            autoplayHoverPause: true,\r\n                                nav: true,\r\n            navSpeed: 1000,\r\n            navText: ['<i class=\"fas fa-chevron-left\"><\/i>', '<i class=\"fas fa-chevron-right\"><\/i>'],\r\n                                dots: true,\r\n            dotsSpeed: 1200,\r\n                                                    rtl: false,\r\n          \r\n        });\r\n      });\r\n    <\/script>\r\n  <\/div>\r\n","protected":false},"excerpt":{"rendered":"<p>Quick Overview:The blog introduces dependency injection in .NET Core, its advantages, and the need to implement it. Further, [&hellip;]<\/p>\n  <div class=\"related-post slider\">\r\n        <div class=\"headline\">Related Posts<\/div>\r\n    <div class=\"post-list owl-carousel\">\r\n\r\n            <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-java-technology\">\r\n\r\n      <img width=\"1200\" height=\"800\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" decoding=\"async\" loading=\"lazy\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1.jpg 1200w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-300x200.jpg 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-1024x683.jpg 1024w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2021\/12\/web-security-partner-1-768x512.jpg 768w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\".Net Core vs. Java \u2013 Which One You Should Use for Your Projects?\" href=\"https:\/\/positiwise.com\/blog\/net-core-vs-java-technology\">\r\n        .Net Core vs. Java \u2013 Which One You Should Use for Your Projects?  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"Precise Road Map for ASP.NET Developers\" href=\"https:\/\/positiwise.com\/blog\/roadmap-for-asp-dot-net-developers\">\r\n\r\n      <img width=\"1021\" height=\"621\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\"Hire ASP.NET Developers - A Precise Road Map to Employ ASP.NET Developers\" decoding=\"async\" loading=\"lazy\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1.jpg 1021w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1-300x182.jpg 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/dealership-1200x800-1-768x467.jpg 768w\" sizes=\"auto, (max-width: 1021px) 100vw, 1021px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"Precise Road Map for ASP.NET Developers\" href=\"https:\/\/positiwise.com\/blog\/roadmap-for-asp-dot-net-developers\">\r\n        Precise Road Map for ASP.NET Developers  <\/a>\r\n\r\n        <\/div>\r\n              <div class=\"item\">\r\n            <div class=\"thumb post_thumb\">\r\n    <a  title=\"A Descriptive Guide to .NET Framework\" href=\"https:\/\/positiwise.com\/blog\/a-descriptive-guide-to-dot-net-framework\">\r\n\r\n      <img width=\"1021\" height=\"621\" src=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/a-descriptive-guide-to-dot-net-framework.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\"A Descriptive Guide to .NET Framework\" decoding=\"async\" loading=\"lazy\" srcset=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/a-descriptive-guide-to-dot-net-framework.jpg 1021w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/a-descriptive-guide-to-dot-net-framework-300x182.jpg 300w, https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2022\/01\/a-descriptive-guide-to-dot-net-framework-768x467.jpg 768w\" sizes=\"auto, (max-width: 1021px) 100vw, 1021px\" \/>\r\n\r\n    <\/a>\r\n  <\/div>\r\n\r\n  <a class=\"title post_title\"  title=\"A Descriptive Guide to .NET Framework\" href=\"https:\/\/positiwise.com\/blog\/a-descriptive-guide-to-dot-net-framework\">\r\n        A Descriptive Guide to .NET Framework  <\/a>\r\n\r\n        <\/div>\r\n      \r\n  <\/div>\r\n\r\n  <script>\r\n      <\/script>\r\n  <style>\r\n    .related-post {}\r\n\r\n    .related-post .post-list {\r\n      text-align: left;\r\n          }\r\n\r\n    .related-post .post-list .item {\r\n      margin: 5px;\r\n      padding: 0px;\r\n          }\r\n\r\n    .related-post .headline {\r\n      font-size: 2rem !important;\r\n      color: #212529 !important;\r\n          }\r\n\r\n    .related-post .headline {\r\nmargin-top: 0;\r\npadding-left: 1%;\r\n}.related-post .post-list .item .post_thumb {\r\n      max-height: 220px;\r\n      margin: 0px 0px 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n          }\r\n\r\n    .related-post .post-list .item .post_title {\r\n      font-size: 1rem;\r\n      color: #212529;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .post-list .item .post_excerpt {\r\n      font-size: 13px;\r\n      color: #3f3f3f;\r\n      margin: 10px 0px;\r\n      padding: 0px;\r\n      display: block;\r\n      text-decoration: none;\r\n          }\r\n\r\n    .related-post .owl-dots .owl-dot {\r\n          }\r\n\r\n      <\/style>\r\n      <script>\r\n      jQuery(document).ready(function($) {\r\n        $(\".related-post .post-list\").owlCarousel({\r\n          items: 3,\r\n          responsiveClass: true,\r\n          responsive: {\r\n            0: {\r\n              items: 1,\r\n            },\r\n            768: {\r\n              items: 2,\r\n            },\r\n            1200: {\r\n              items: 3,\r\n            }\r\n          },\r\n                      rewind: true,\r\n                                loop: true,\r\n                                center: true,\r\n                                autoplay: true,\r\n            autoplayHoverPause: true,\r\n                                nav: true,\r\n            navSpeed: 1000,\r\n            navText: ['<i class=\"fas fa-chevron-left\"><\/i>', '<i class=\"fas fa-chevron-right\"><\/i>'],\r\n                                dots: true,\r\n            dotsSpeed: 1200,\r\n                                                    rtl: false,\r\n          \r\n        });\r\n      });\r\n    <\/script>\r\n  <\/div>\r\n","protected":false},"author":3,"featured_media":13939,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_eb_attr":"","footnotes":""},"categories":[7],"tags":[],"class_list":["post-13930","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dot-net-development"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Dependency injection in .NET Core Explained with Code Examples<\/title>\n<meta name=\"description\" content=\"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Dependency injection in .NET Core Explained with Code Examples\" \/>\n<meta property=\"og:description\" content=\"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example\" \/>\n<meta property=\"og:site_name\" content=\"Positiwise\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/positiwise\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-12T08:52:52+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-27T08:50:19+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1021\" \/>\n\t<meta property=\"og:image:height\" content=\"621\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Parag Mehta\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@positiwise\" \/>\n<meta name=\"twitter:site\" content=\"@positiwise\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Parag Mehta\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example\"},\"author\":{\"name\":\"Parag Mehta\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#\\\/schema\\\/person\\\/b4b3d9970ea94f5914a615f70345353a\"},\"headline\":\"What is Dependency Injection in .NET Core? &#8211; Explained with Code Examples\",\"datePublished\":\"2023-10-12T08:52:52+00:00\",\"dateModified\":\"2023-12-27T08:50:19+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example\"},\"wordCount\":1684,\"publisher\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/10\\\/dependency-injection-in-dot-net-core.jpg\",\"articleSection\":[\".NET Development\"],\"inLanguage\":\"en-US\",\"copyrightYear\":\"2022\",\"copyrightHolder\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#organization\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example\",\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example\",\"name\":\"Dependency injection in .NET Core Explained with Code Examples\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/10\\\/dependency-injection-in-dot-net-core.jpg\",\"datePublished\":\"2023-10-12T08:52:52+00:00\",\"dateModified\":\"2023-12-27T08:50:19+00:00\",\"description\":\"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#primaryimage\",\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/10\\\/dependency-injection-in-dot-net-core.jpg\",\"contentUrl\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/10\\\/dependency-injection-in-dot-net-core.jpg\",\"width\":1021,\"height\":621,\"caption\":\"Dependency Injection in .NET Core\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/dependency-injection-in-net-core-with-example#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/positiwise.com\\\/blog\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"What is Dependency Injection in .NET Core? &#8211; Explained with Code Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/\",\"name\":\"Positiwise\",\"description\":\"Providing Full-cycle Software Development Services\",\"publisher\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#organization\"},\"alternateName\":\"Positiwise Software Pvt Ltd\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#organization\",\"name\":\"Positiwise\",\"alternateName\":\"Positiwise Software Pvt Ltd\",\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo.png\",\"contentUrl\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo.png\",\"width\":202,\"height\":29,\"caption\":\"Positiwise\"},\"image\":{\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/positiwise\\\/\",\"https:\\\/\\\/x.com\\\/positiwise\",\"https:\\\/\\\/github.com\\\/positiwise\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/positiwise\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/#\\\/schema\\\/person\\\/b4b3d9970ea94f5914a615f70345353a\",\"name\":\"Parag Mehta\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g\",\"caption\":\"Parag Mehta\"},\"description\":\"Parag Mehta, the CEO and Founder of Positiwise Software Pvt Ltd has extensive knowledge of the development niche. He is implementing custom strategies to craft highly-appealing and robust applications for its clients and supporting employees to grow and ace the tasks. He is a consistent learner and always provides the best-in-quality solutions, accelerating productivity.\",\"sameAs\":[\"https:\\\/\\\/www.linkedin.com\\\/in\\\/paragcmehta\"],\"url\":\"https:\\\/\\\/positiwise.com\\\/blog\\\/author\\\/parag-mehta\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Dependency injection in .NET Core Explained with Code Examples","description":"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example","og_locale":"en_US","og_type":"article","og_title":"Dependency injection in .NET Core Explained with Code Examples","og_description":"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.","og_url":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example","og_site_name":"Positiwise","article_publisher":"https:\/\/www.facebook.com\/positiwise\/","article_published_time":"2023-10-12T08:52:52+00:00","article_modified_time":"2023-12-27T08:50:19+00:00","og_image":[{"width":1021,"height":621,"url":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg","type":"image\/jpeg"}],"author":"Parag Mehta","twitter_card":"summary_large_image","twitter_creator":"@positiwise","twitter_site":"@positiwise","twitter_misc":{"Written by":"Parag Mehta","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#article","isPartOf":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example"},"author":{"name":"Parag Mehta","@id":"https:\/\/positiwise.com\/blog\/#\/schema\/person\/b4b3d9970ea94f5914a615f70345353a"},"headline":"What is Dependency Injection in .NET Core? &#8211; Explained with Code Examples","datePublished":"2023-10-12T08:52:52+00:00","dateModified":"2023-12-27T08:50:19+00:00","mainEntityOfPage":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example"},"wordCount":1684,"publisher":{"@id":"https:\/\/positiwise.com\/blog\/#organization"},"image":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#primaryimage"},"thumbnailUrl":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg","articleSection":[".NET Development"],"inLanguage":"en-US","copyrightYear":"2022","copyrightHolder":{"@id":"https:\/\/positiwise.com\/blog\/#organization"}},{"@type":"WebPage","@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example","url":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example","name":"Dependency injection in .NET Core Explained with Code Examples","isPartOf":{"@id":"https:\/\/positiwise.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#primaryimage"},"image":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#primaryimage"},"thumbnailUrl":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg","datePublished":"2023-10-12T08:52:52+00:00","dateModified":"2023-12-27T08:50:19+00:00","description":"Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.","breadcrumb":{"@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#primaryimage","url":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg","contentUrl":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/10\/dependency-injection-in-dot-net-core.jpg","width":1021,"height":621,"caption":"Dependency Injection in .NET Core"},{"@type":"BreadcrumbList","@id":"https:\/\/positiwise.com\/blog\/dependency-injection-in-net-core-with-example#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/positiwise.com\/blog"},{"@type":"ListItem","position":2,"name":"What is Dependency Injection in .NET Core? &#8211; Explained with Code Examples"}]},{"@type":"WebSite","@id":"https:\/\/positiwise.com\/blog\/#website","url":"https:\/\/positiwise.com\/blog\/","name":"Positiwise","description":"Providing Full-cycle Software Development Services","publisher":{"@id":"https:\/\/positiwise.com\/blog\/#organization"},"alternateName":"Positiwise Software Pvt Ltd","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/positiwise.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/positiwise.com\/blog\/#organization","name":"Positiwise","alternateName":"Positiwise Software Pvt Ltd","url":"https:\/\/positiwise.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/positiwise.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/07\/logo.png","contentUrl":"https:\/\/positiwise.com\/blog\/wp-content\/uploads\/2023\/07\/logo.png","width":202,"height":29,"caption":"Positiwise"},"image":{"@id":"https:\/\/positiwise.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/positiwise\/","https:\/\/x.com\/positiwise","https:\/\/github.com\/positiwise","https:\/\/www.linkedin.com\/company\/positiwise"]},{"@type":"Person","@id":"https:\/\/positiwise.com\/blog\/#\/schema\/person\/b4b3d9970ea94f5914a615f70345353a","name":"Parag Mehta","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/072ea4a638415a77610a840228d51b8225ad88856ed34d69cbe1fcd638390535?s=96&r=g","caption":"Parag Mehta"},"description":"Parag Mehta, the CEO and Founder of Positiwise Software Pvt Ltd has extensive knowledge of the development niche. He is implementing custom strategies to craft highly-appealing and robust applications for its clients and supporting employees to grow and ace the tasks. He is a consistent learner and always provides the best-in-quality solutions, accelerating productivity.","sameAs":["https:\/\/www.linkedin.com\/in\/paragcmehta"],"url":"https:\/\/positiwise.com\/blog\/author\/parag-mehta"}]}},"_links":{"self":[{"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/posts\/13930","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/comments?post=13930"}],"version-history":[{"count":13,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/posts\/13930\/revisions"}],"predecessor-version":[{"id":14650,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/posts\/13930\/revisions\/14650"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/media\/13939"}],"wp:attachment":[{"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/media?parent=13930"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/categories?post=13930"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/positiwise.com\/blog\/wp-json\/wp\/v2\/tags?post=13930"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}