What is dependency injection in asp.net core.
Loading
What is dependency injection in asp.net core.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Dharmeshwaran SRank #819 · 2.8K reputationPosted Jun 23, 2024, 4:58 AM EDT
Dependency Injection is the Technique not only specific to .net. It is used across multiple languages
Dependency Injection (DI) is a design pattern used to implement Inversion of Control (IoC). It allows a class to receive its dependencies from an external source rather than creating them itself. This leads to more modular, testable, and maintainable code.
Simple Explanation
Imagine you have a car, and the car needs an engine to function. Instead of the car creating its own engine, it receives an engine from outside. This way, you can easily swap the engine with another one if needed, and you can test the car by providing a mock engine.
Basic Components of DI
Example in C#
Let's see a simple example in C# without using any DI framework.
Without Dependency Injection
In this example, the
Carclass creates its ownEngine.public class Engine { public void Start() => Console.WriteLine("Engine started"); } public class Car { private Engine _engine; public Car() { _engine = new Engine(); // Car creates its own Engine } public void Start() { _engine.Start(); } } public class Program { public static void Main() { var car = new Car(); car.Start(); } }With Dependency Injection
Here, the
Engineis injected into theCarfrom the outside.public class Engine { public void Start() => Console.WriteLine("Engine started"); } public class Car { private Engine _engine; // Constructor injection public Car(Engine engine) { _engine = engine; // Engine is injected } public void Start() { _engine.Start(); } } public class Program { public static void Main() { var engine = new Engine(); var car = new Car(engine); // Engine is provided by the injector car.Start(); } }Types of Dependency Injection
Benefits of Dependency Injection
In summary, Dependency Injection is a powerful pattern that helps to create flexible, testable, and maintainable code by externalizing the creation and management of dependencies.
Jaydeep PatilRank #205 · 11.7K reputationPosted Jun 24, 2024, 8:02 AM EDT
Hi,
Please have a look into my below article to understand DI in detail with some practical examples.
https://www.c-sharpcorner.com/blogs/dependency-injection-using-net-core-api