Skip to content

Dependency Injection examples in .NET for both Console and Web API projects, demonstrating clean architecture.

Notifications You must be signed in to change notification settings

sinanganiz/dependency-injection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Dependency Injection Examples in .NET

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!

πŸ—‚οΈ Project Structure

.
β”œβ”€β”€ ConsoleAppDI/
β”œβ”€β”€ WebApiDI/
β”œβ”€β”€ dependency-injection.sln
└── README.md

πŸ’‘ About Dependency Injection

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:

  • EmailSender
  • SmsSender

πŸš€ How to Run

You can run any example individually.

πŸ“Œ Prerequisites

.NET 9 SDK

▢️ Run ConsoleAppDI

cd ConsoleAppDI
dotnet run

You 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>();

▢️ Run WebApiDI

cd WebApiDI
dotnet run

Once 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>();

πŸ“‚ Core Concepts Demonstrated

Constructor Injection

Interface-based abstraction (IMessageSender)

Manual vs Built-in DI container

Loose coupling

About

Dependency Injection examples in .NET for both Console and Web API projects, demonstrating clean architecture.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages