2

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.

Buildstarted
  • 25,661
  • 9
  • 79
  • 93

1 Answers1

3

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.

Community
  • 1
  • 1
Mark Seemann
  • 209,566
  • 41
  • 390
  • 671
  • Agreed. I added all the overloads and it's working just fine. As of now there's only two dependencies and I don't think more will be needed. I just didn't want to require all dependencies to be provided since I've already written some basic ones...Your linked answer is really interesting and it making me rethink part of my approach to this project. Might make management a bit easier. I'll accept sometime tomorrow if no other answers come forth but for now. +1 (on both) – Buildstarted Jul 07 '11 at 05:29
  • Ok, I really wish I could upvote you again :) I've talked it over with someone and he's come to the same conclusion about `SRP`. So minor changes are on the way. Thanks! – Buildstarted Jul 07 '11 at 05:37