Dependency InjectionAnd using an Inversion of Control (IoC) container
What is Dependency InjectionGiving an object instance it’s variables
Dependency Non-Injectionpublic class Whatever{  private DbStuff _db;   This is a variable  public Whatever() {   _db = new DbStuff();   And Whatever }                          depends on itso it creates it  public void DoIt() {   _db.GetData(); }}
And this is bad for all kinds of reasons…
Single Responsibility PrincipleA class should have one, and only one, reason to change.We switch from SQL Server to Oracle and our Whatever class needs to change
Dependency Injectionpublic class Whatever{  private DbStuff_db;  public Whatever(DbStuff database) {   _db = database;   The ‘new’ keyword }                     is outta there  public void DoIt() {   _db.GetData(); }}
WinOur Whateverclass still depends on DbDatabut it is not responsible for itBy adhering to SRP through dependency injection we increasecohesion
But wait! We still have a problem
Dependency Inversion PrincipleDepend on abstractions, not on concretions.We can improve the situation by depending on an interface or abstract class
Dependency Injection v 2.0public class Whatever{  private IDbStuff _db;    Better  public Whatever(IDbStuff database) {   _db = database;   life is good }  public void DoIt() {   _db.GetData(); }}
To summarize, DI is about passing instance variables
BenefitsHigh cohesion because classes are focused on doing one thing really wellTestabilityIDbStuff data = new FakeDbWithBadData();var test = new Whatever(data);Assert.Throws(Exception,test.DoIt());The class under test did not have to change. Magic!
private readonlySystemConfiguration _configuration;private readonlyIWorkorderEntityBuilder _entityBuilder;public NewEntityWorkorderManager(IWorkorderRepositoryworkorderRepository,IMessageRepositorymessageRepository,IWorkorderEntityBuilderentityBuilder,SystemConfiguration configuration,ICityworksRepositorycityworksRepository): base(workorderRepository, messageRepository,cityworksRepository, configuration)        {            _entityBuilder = entityBuilder;            _configuration = configuration;        }
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.)
Manage DependenciesDI makes for cohesive, loosely couple softwareBut also more moving partsIoC containers exist to make dependency injection easier and more predictable
ContainersA Short ListSpringSpring.NETPicoCastle WindsorStructureMapNinjectAutofacUnityGlassfish and any EJB 3.0 app server
Workflow
ForRequestedType<ISpatialQuery>()                .TheDefaultIsConcreteType<SpatialQueryGenericClient>();
ForRequestedType<ISettingRepository>()                .TheDefault.Is.OfConcreteType<ApplicationSettingRepository>()                .CtorDependency<IUnitOfWork>("unitOfWork")                .Is(u => u.TheInstanceNamed(Resources.WCSDatasource));
var settings = ObjectFactory.GetInstance<ISettingRepository>();
Autowiring Is A Big Win
Things depend on things depend on things…varprocessor = ObjectFactory.GetInstance<IMessageProcessor>();
FeaturesMany other features but that’s the coreManage lifetime of objectsSingleton, per-thread, per-sessionXML configuration

Dev Cast Dependency Injection

  • 1.
    Dependency InjectionAnd usingan Inversion of Control (IoC) container
  • 2.
    What is DependencyInjectionGiving an object instance it’s variables
  • 3.
    Dependency Non-Injectionpublic classWhatever{ private DbStuff _db;  This is a variable public Whatever() { _db = new DbStuff();  And Whatever } depends on itso it creates it public void DoIt() { _db.GetData(); }}
  • 4.
    And this isbad for all kinds of reasons…
  • 5.
    Single Responsibility PrincipleAclass 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 Injectionpublic classWhatever{ private DbStuff_db; public Whatever(DbStuff database) { _db = database;  The ‘new’ keyword } is outta there public void DoIt() { _db.GetData(); }}
  • 7.
    WinOur Whateverclass stilldepends on DbDatabut it is not responsible for itBy adhering to SRP through dependency injection we increasecohesion
  • 8.
    But wait! Westill have a problem
  • 9.
    Dependency Inversion PrincipleDependon abstractions, not on concretions.We can improve the situation by depending on an interface or abstract class
  • 10.
    Dependency Injection v2.0public class Whatever{ private IDbStuff _db;  Better public Whatever(IDbStuff database) { _db = database;  life is good } public void DoIt() { _db.GetData(); }}
  • 11.
    To summarize, DIis about passing instance variables
  • 12.
    BenefitsHigh cohesion becauseclasses are focused on doing one thing really wellTestabilityIDbStuff data = new FakeDbWithBadData();var test = new Whatever(data);Assert.Throws(Exception,test.DoIt());The class under test did not have to change. Magic!
  • 13.
    private readonlySystemConfiguration _configuration;privatereadonlyIWorkorderEntityBuilder _entityBuilder;public NewEntityWorkorderManager(IWorkorderRepositoryworkorderRepository,IMessageRepositorymessageRepository,IWorkorderEntityBuilderentityBuilder,SystemConfiguration configuration,ICityworksRepositorycityworksRepository): base(workorderRepository, messageRepository,cityworksRepository, configuration) { _entityBuilder = entityBuilder; _configuration = configuration; }
  • 14.
    Inversion of ControlContainers(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 DependenciesDI makesfor cohesive, loosely couple softwareBut also more moving partsIoC containers exist to make dependency injection easier and more predictable
  • 16.
    ContainersA Short ListSpringSpring.NETPicoCastleWindsorStructureMapNinjectAutofacUnityGlassfish and any EJB 3.0 app server
  • 17.
  • 18.
    ForRequestedType<ISpatialQuery>() .TheDefaultIsConcreteType<SpatialQueryGenericClient>();
  • 19.
    ForRequestedType<ISettingRepository>() .TheDefault.Is.OfConcreteType<ApplicationSettingRepository>() .CtorDependency<IUnitOfWork>("unitOfWork") .Is(u => u.TheInstanceNamed(Resources.WCSDatasource));
  • 20.
    var settings =ObjectFactory.GetInstance<ISettingRepository>();
  • 21.
  • 22.
    Things depend onthings depend on things…varprocessor = ObjectFactory.GetInstance<IMessageProcessor>();
  • 23.
    FeaturesMany other featuresbut that’s the coreManage lifetime of objectsSingleton, per-thread, per-sessionXML configuration