This repository demonstrates Dependency Injection (DI) in .NET using two separate projects:
ConsoleAppDI/: A lightweight console application that manually sets up DI.WebApiDI/: An ASP.NET Core Web API project that leverages built-in DI features.
The goal is to showcase how DI can help build loosely coupled, maintainable, and testable applications in both minimal and full-featured .NET environments.
π These examples are also explained in detail in the blog post:
π Read the blog post here!
.
βββ ConsoleAppDI/
βββ WebApiDI/
βββ dependency-injection.sln
βββ README.md
Dependency Injection is a software design pattern that allows a class to receive its dependencies from an external source rather than creating them itself. This promotes:
- Separation of concerns
- Code reuse and testability
- Flexibility in switching implementations
Both projects here use the same abstraction: IMessageSender, with two implementations:
EmailSenderSmsSender
You can run any example individually.
.NET 9 SDK
cd ConsoleAppDI
dotnet runYou will see output like:
Email sent: Hello Dependency Injection!To switch to SmsSender, edit the DI registration line in Program.cs:
services.AddTransient<IMessageSender, SmsSender>();cd WebApiDI
dotnet runOnce the API is running, you can send a POST request to:
POST https://localhost:5001/api/notification
Content-Type: application/json
"Hello from Web API!"Expected console output:
Email sent: Hello from Web API!To use SmsSender, change the registration in Program.cs:
builder.Services.AddTransient<IMessageSender, SmsSender>();Constructor Injection
Interface-based abstraction (IMessageSender)
Manual vs Built-in DI container
Loose coupling