##### DEPENDENCY INJECTION ####
-----------------------------------------
🧠 What Is a DI Container?
A Dependency Injection (DI) container is a framework-provided object manager that:
- Stores registrations of services and their lifetimes
- Resolves dependencies automatically when needed
- Creates and injects objects into classes that depend on them
Think of it as a smart factory that knows how to build your objects, wire them
together, and manage their lifetimes—all without you manually instantiating
anything.
How It Works in C#
C# uses IServiceCollection to register services and IServiceProvider to resolve
them.
Lifecycle
🔹 Transient
[Link]<IService, MyService>();
- A new instance is created every time it's injected.
- Good for stateless or short-lived operations.
- Can lead to higher memory usage if overused.
🔸 Scoped
[Link]<IService, MyService>();
- A single instance per request.
- Shared across all components in the same HTTP request.
- Ideal for web apps where you want to maintain state per user request.
🔶 Singleton
[Link]<IService, MyService>();
- A single instance is created and reused forever.
- Great for configuration, caching, or logging.
- Be careful with stateful services—can cause thread safety issues.
Where to Register Service
You’ll typically register services in [Link]:
var builder = [Link](args);
// Register services
[Link]<IEngine, ElectricEngine>();
[Link]<IRepository, SqlRepository>();
[Link]<ILogger, ConsoleLogger>();
var app = [Link]();