I'm trying to come to terms with using IoC/Dependency Injection while at the same time programming to contracts rather than specific classes. The dilemma I'm having is the tension between:
Do program to interfaces for IoC: I started out with IoC relying heavily on interfaces. Judging by Spring's sample projects, interfaces are the way to go when programing to a contract with IoC.
( ... although abstract classes generally preferred: the main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for evolution of APIs )
Do make class dependencies explicit via constructor My gut feeling is that it's good programming practice to pass dependencies in to a class's constructor. Indeed, this is dependency injection.
... except you can't enforce constructor signature in interfaces/abstract clases: Neither interfaces or nor abstract classes allow for defining a constructor signature ( easily / elegantly ). See also Framework Design Guidelines section 4.4: DO NOT define public or protected internal constructors in abstract types. ... Constructors should be public only if users will need to create instances of the type.
This question is related to a previous stackoverflow question: Interface defining a constructor signature?
But my question is:
Since you can't define a constructor in a C# interface/abstract class, as the question above asks, on a practical level:
How do you reconcile this with the sensible practice of passing dependencies in via a constructor?
Edit: Thank you for the answers. I'm hoping for some insight on what I should do in this case. Just not use contructor args? Use some sort of Init() method that does take the dependencies? Edit2: Thanks for the great answers, very helpful.