dependency injection - Why inject dependencies? -


assuming i'm using ioc container, why must types have dependencies injected? why can't every type assume container exists , retrieve dependencies needs itself? disadvantages latter approach?

i'm aware of property injection don't want suggested answer though save on having long parameter list constructors in more complex types. , doesn't save on code need type/maintain. oh, , i'd prefer have dependencies readonly/final (personal preference).

so here's typical example of constructor injection in c#:

public class calculator {     private readonly iadder _adder;     private readonly isubtractor _subtractor;     private readonly imultiplier _multiplier;     private readonly idivider _divider;      public calculator(iadder adder, isubtractor subtractor,                       imultiplier multiplier, idivider divider)     {         _adder = adder;         _subtractor = subtractor;         _multiplier = multiplier;         _divider = divider;     } } 

and here's i'd rather do:

public class calculator {     private readonly iadder _adder;     private readonly isubtractor _subtractor;     private readonly imultiplier _multiplier;     private readonly idivider _divider;      public calculator()     {         _adder = container.get<iadder>();         _subtractor = container.get<isubtractor>();         _multiplier = container.get<imultiplier>();         _divider = container.get<idivider>();     } } 

i'd maintain list of pros , cons answers come in:

pros

  • clean constructors types need not "pollute" constructors dependencies. it's not big problem here because calculator doesn't have in constructor other dependencies imagine did. e.g. public calculator(mode mode, bool usedigitgrouping).
  • client code doesn't break when dependency's dependencies change.
  • less code maintain.

cons:

  • harder change ioc container in future.
  • it's not clear type's dependencies are.

assuming i'm using ioc container, why must types have dependencies injected? why can't every type assume container exists , retrieve dependencies needs itself? disadvantages this?

a couple of reasons can think of, of mention one:

  • it's no longer apparent dependencies class has, if any
  • the class assume hidden dependency on container, of worst kind no less (assuming either exists global or accessible statically)

your concern regarding how easy adapt code when dependency's dependencies change valid; that's strong argument ioc (let container automatically; long it's possible satisfy dependencies nothing break).


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -