Reputation: 26689
In an external library I have a controller that requires two repository dependencies. The default constructor resolves those dependencies just fine by calling a simple factory to create the dependencies. I want to give subscribers to my library the ability to override any of the dependencies but use the default dependencies when they're not overridden.
So for an example:
public class LibraryController {
public LibraryController(IRepository1 repo1, IRepository2 repo2) {
}
}
They might override IRepository1
but not IRepository2
. I do not either understand enough of Dependency Injection
or I'm just missing something here.
I do not want to force a dependency on Ninject
or StructureMap
or Unity
to create the default dependencies. How can I do this without that?
Edit: I could just create several constructors based on the differing parameters but I was hoping for a different solution.
Upvotes: 2
Views: 260
Reputation: 233202
The default approach in DI would exactly be to create all appropriate overloads. It's easy to do and requires no additional libraries or frameworks. In your case there are only four possible combinations, so that's not too bad.
You might think that this becomes unwieldy as the number of constructor parameters grow, but you shouldn't have too many dependencies in the first place.
As a general rule, when using Constructor Injection it's better to expose only the injection constructor and remove the defaults. Combining DI and default constructors is a design smell I call Bastard Injection. It's rarely the correct approach.
Upvotes: 3