Most Dependency Injection (DI) frameworks offer two ways to inject concrete classes into your objects: constructor injection and property injection (a.k.a. setter injection).
Barring very unusual circumstances, constructor injection is better.
Before stating the reasons why, let's review how constructor and property injection look with the Microsoft Unity DI framework. With constructor injection, the interface or abstract type is a parameter to the constructor; with property injection, the property is decorated with the [Dependency] attribute.
public class MyClass : IMyClass
{
// When you resolve IMyClass to get MyClass,
// Unity will see the [Dependency] attribute and set
// this property to an instance of the concrete type
// that you have registered for IMyInterface in the
// Unity container.
[Dependency]
public IMyInterface PropertyInjected { get; set; }
readonly private IMyInterface _constructorInjected;
// When you resolve IMyClass to get MyClass, Unity
// will also see that MyClass' constructor takes an
// interface parameter. As with property injection,
// it will fill the parameter with an instance of
// whatever type you have registered for
// that interface.
public MyClass(IMyInterface constructorInjected)
{
Contract.Requires(constructorInjected != null);
_constructorInjected = constructorInjected;
}
}
So why is constructor injection better?
First, it requires no special attributes like [Dependency]. This may sound trivial, but it's not. The presence of [Dependency] drags in the whole Unity library. That means that nobody can use your class without linking to Unity. (Other DI frameworks will have similar problems; they all use attributes for property injection.) It also means that your class will not work with a different DI framework.
Assuming that PropertyInjected is there for a purpose, the consumer of this class has two choices: he can have Unity set it for him, or he must set it on his own. Either way, what he must do won't be obvious. With constructor injection, intellisense and the compiler will both help you out. With property injection, you won't know that you forgot something until your program fails at runtime. On my team, we have found that discoverability is very important. If you write code that is consumed by others, you do everyone a favor if they can see at intellisense time what your code requires.
Finally, property injection violates the Single Responsibility Principle. The class that uses it has three responsibilities. First, it has taken upon itself the responsibility of choosing your DI software. Second, it must gather its dependencies from the DI container. And what was the third responsibility? (Oops.) Oh yeah -- it also does whatever you conceived as its primary task.
If you can think of a good reason for using property injection, please let me know in the comments. In the meantime, I think you'll be very happy with constructor injection.