Mark Seemann - Dependency Injection in .NET
DI Definition Dependency Injection is a set of software design principles and patterns that enable us to develop loosely coupled code. * DI Container is not required. * Inversion of Control is a wider term than Dependency Injection.
Benefits of DI Late binding Services can be swapped with other services. Extensibility & Maintainability Code can be extended and reused in ways not explicitly planned for. Classes with clearly defined responsibilities are easier to maintain. Parallel development Code can be developed in parallel. Testability Classes can be unit tested.
Stable & Volatile Dependencies Stable dependency satisfies all these rules: The class or module already exists. You expect that new versions won’t contain breaking changes. The types in question contain deterministic algorithms. You never expect to have to replace the class or module with another. If dependency does not satisfy one or several points from above list, then it’s a volatile dependency that should be injected.
Configuring DI Containers
Configuration ways: pros & cons
Composition Root
Register Resolve Release
DI Patterns Constructor Injection Property Injection Method Injection Ambient Injection
Constructor Injection
Property Injection
Property Injection usage Unity DependencyAttribute
Method Injection
Ambient Context
Choosing DI pattern
DI anti-pattern: Control Freak
DI anti-pattern: Bastard Injection
DI anti-pattern: Constrained Construction *Is only applicable for late binding.
DI anti-pattern: Service Locator
DI refactorings (challenges) Mapping runtime value to ABSTRACTIONS Route algorithm example. Use Abstract Factory. Working with short-lived DEPENDENCIES Connections, clients, etc. Use Abstract Factory. Resolving cyclic DEPENDENCIES Break dependency through Property Injection.
Object Composition Console application ASP.NET MVC application WCF service WPF application ASP.NET application PowerShell cmdlets
Lifestyle catalog
Interception
Cross-Cutting Concerns
DI Container Feature comparison