Dependency Injection & SOLID

SOLID DI Cover
Dependency Injection (DI) is a technique to achieve Inversion Of Control (IOC) between classes and their dependencies. It promotes Loose Coupling by ensuring classes aren't responsible for creating their own dependencies.

Injection Types

  • 1. Constructor Injection: Most recommended and reliable. Enforced at compile-time and keeps objects immutable.
  • 2. Property Injection: Dependencies set after object creation. Useful for frameworks or circular dependencies, but carries null-reference risks.
  • 3. Method Injection: Dependencies passed as parameters. Best when a dependency is only needed for a specific action.

IOC & DI Containers

IoC Container: A tool that automates DI. Instead of the program controlling the flow, an external "Container" resolves and injects dependencies. Examples: Autofac, Unity, Ninject.

Service Lifetimes:

New instance created every time. Best for short-lived, lightweight operations.

One instance per HTTP request. Shared across components within that same request (e.g., DbContext).

One instance shared throughout the entire application lifetime. Ideal for caching and configurations.

AutoFac: Advanced DI

More flexible than built-in DI. Supports RegisterType<T>() for creating new instances and RegisterInstance(obj) for existing objects (Singleton behavior).

SOLID Principles

Coupling: Degree of dependency between components. Goal: Low Coupling (Abstractions).
Cohesion: How related members of a class are. Goal: High Cohesion (Single Responsibility).

S - Single Responsibility: One reason to change. Separate User info from DB logic.

O - Open/Closed: Open for extension, closed for modification.

L - Liskov Substitution: Subtypes must be substitutable for their base types (The Bird/Penguin problem).

I - Interface Segregation: Don't force implementation of unused methods. Split large interfaces.

D - Dependency Inversion: Depend on abstractions, not concretions.