Comparison
Constructor injectionvsSetter injection
Constructor injection
you cannot create the object without giving it what it needs, so there is no moment where it exists half-wired.
Passing dependencies as constructor arguments, making them required and making the object valid from the instant it exists. It is the default choice for almost every case: the parameter list is an honest declaration of what the class needs, and a list that grows uncomfortable is a signal the class does too much. Its one real limitation is circular dependencies, which it makes impossible to construct — usually a design message rather than a problem to work around.
Full entry →Setter injection
the object is constructed first and wired afterwards, so there is a window where calling it throws a null reference.
Supplying dependencies through settable properties after construction. It exists for genuinely optional collaborators and for breaking a construction cycle, and it is worth knowing for both reasons; used by default it produces objects with no valid state guarantee and error messages that point at the wrong moment. Frameworks that inject into private fields by reflection are the same trade with the setter hidden.
Full entry →