3. Dependency Non-Injection public class Whatever { private DbStuff _db; This is a variable public Whatever() { _db = new DbStuff(); And Whatever } depends on it so it creates it public void DoIt() { _db.GetData(); } }
5. Single Responsibility Principle A class should have one, and only one, reason to change. We switch from SQL Server to Oracle and our Whatever class needs to change
6. Dependency Injection public class Whatever { private DbStuff_db; public Whatever(DbStuff database) { _db = database; The ‘new’ keyword } is outta there public void DoIt() { _db.GetData(); } }
7. Win Our Whateverclass still depends on DbDatabut it is not responsible for it By adhering to SRP through dependency injection we increasecohesion
9. Dependency Inversion Principle Depend on abstractions, not on concretions. We can improve the situation by depending on an interface or abstract class
10. Dependency Injection v 2.0 public class Whatever { private IDbStuff _db; Better public Whatever(IDbStuff database) { _db = database; life is good } public void DoIt() { _db.GetData(); } }
12. Benefits High cohesion because classes are focused on doing one thing really well Testability IDbStuff data = new FakeDbWithBadData(); var test = new Whatever(data); Assert.Throws(Exception,test.DoIt()); The class under test did not have to change. Magic!
14. Inversion of Control Containers (IoC is a terrible term but we’re stuck with it. But maybe we’ll use container instead. At least it’s shorter.)
15. Manage Dependencies DI makes for cohesive, loosely couple software But also more moving parts IoC containers exist to make dependency injection easier and more predictable
16. ContainersA Short List Spring Spring.NET Pico Castle Windsor StructureMap Ninject Autofac Unity Glassfish and any EJB 3.0 app server