6. DIP: practical rules 6 No class should derive from a concrete class No variable should hold a reference to a concrete class No method should override an implemented method of any of its base class
7. DIP: Inversion of what ?? 7 before after Injector Consumer also high level component depends on an abstraction high level component depens on low level components (concrete classes) interface new() new() new() concrete classes depend on an abstraction Dep1 Dep2 Dep2 Dep1 Dep2 Dep2
8. DIP: a diagram 8 Take a look at the class diagram concrete classes depend on an abstraction
9. DIP: Who 9 This guy is not a preacher or a wizard: Martin Fowler (*) He gave us three main styles(**) of dependency injection : Interface Injection Setter Injection Constructor Injection (*) but he is still waiting for a call from hollywood (**) and many other things...
10. DIP: Interface Injection (Type 1) 10 publicinterfaceIInjector { voidInjectDependency(IDependentdependent); } publicclassInjector : IInjector { privateIDependent_dependent; publicvoidInjectDependency(IDependentdependent) { _dependent = dependent; } publicvoidDoSomething() { _dependent.DoSomethingInDependent(); } } With this technique we define and use interfaces Let’s define an interface to perform injection Injector implements the interface
11. DIP: Interface Injection (Type 1) 11 Get the correnct dependency based on config file Create our main class and inject the dependency the method references the dependency, so behaviour depends on the config file IDependentdependency = GetCorrectDependency(); Injectorinjector = newInjector(); injector.InjectDependency(dependency); injector.DoSomething(); Configuration file: <?xml version="1.0"encoding="utf-8" ?> <configuration> <appSettings> <add key="ClassName"value="DIP.InterfaceInjection.DependentClass1" /> </appSettings> </configuration>
12. DIP: Setter Injection (Type 2) 12 publicclassInjector { privateIDependent_dependent; publicIDependentDependent { get { return_dependent; } set { _dependent = value; } } publicvoidDoSomething() { Dependent.DoSomethingInDependent(); } } Client class has a property Create our main class and inject the dependency IDependentdependency = GetCorrectDependency(); Injectorinjector = newInjector(); injector.Dependent = dependency; injector.DoSomething();
13. DIP: Constructor Injection (Type 3) 13 publicclassInjector { privateIDependent_dependent; publicInjector(IDependentdependent) { _dependent = dependent; } publicvoidDoSomething() { _dependent.DoSomethingInDependent(); } } Client class has nothins else a constructor to inject dependency Create our main class and passing dependency through constructor IDependentdependency = GetCorrectDependency(); Injectorinjector = newInjector(dependency); injector.DoSomething();
14. DIP: Links and conclusions 14 Inversion of Control Containers and the Dependency Injection pattern Introduction to Dependency Injection by Rich Newman Images from Wacky.com