5. What?
public class ExampleClass
{
private Logger logger;
public ExampleClass()
{
this.logger = new Logger();
this.logger.Log(“Constructor call”);
}
}
public class ExampleClass
{
private ILogger logger;
public ExampleClass(ILogger logger)
{
this.logger = logger;
if (logger == null)
{
throw new ArgumentNullException(“logger”);
}
this.logger.Log(“Constructor call”);
}
}
Original What we aim for
6. Why?
Problem
Constraints
Updating ServiceA ,need to update ClassA.
Need implementation in compile time.
Not easily testable
Repetitive code for creation.
Tightly coupled
ClassA
SerivceA
ServiceB
Uses
7. Benefits
Benefit Description
Late Binding Services can be swapped depending on needs.
Extensibility Code can be extended and reused.
Parallel development Code can be developed in parallel.
Maintainability Clearly defined classes are easy to maintain.
Testability Unit testing is possible.
8. Dependency inversion principle (SOLID)
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.
11. Constructor injection
This is the most common DI.
Injection DEPENDENCY through the class’s constructor when instantiating that class.
Should be used when the injected dependency is required for the class to function.
Solves most INJECTION goals
12. Method injection
Inject the dependency into a single method.
Whole class does not
Generally uncommon, usually used for edge cases.
public class ContactManager : IContactManager
{
….
public bool Save(IContactPersistence contactDatabaseService,
IContact contact)
{
if (logger == null)
{
throw new ArgumentNullException(“logger”);
}
…. // Additional business logic executed before calling the save
return contactDatabaseService.Save(contact);
}
}
13. Property injection
Also called Setter injection.
Used when a class has optional dependencies(Swappable).
Requires NULL checking.
Does not require adding or modifying constructors.
14. Why Not?
Harder to read
More entities to manage
You need to ensure dependencies can be resolved.
Certain implementations can have performance drawbacks.