0

Considering a solution that has some manual DI going on such as the below class, is there a better way of managing the concrete implementations without adding a container. This is theoretical, there is no real test case but something I was thinking of earlier.

The below DI example is fine, however it's preferred that concrete classes are kept to the composition root and not scattered across an application. Is there a way to achieve that without a container, or is this bit of a wild goose chase and containers are required if you want to achieve this objective?

public class SomeClass
{
    public SomeClass:this(new Something())
    {}

    public SomeClass(ISomething something)
    {
       //logic here
    }
}

//update My question is not a duplication of the linked one. I will try to elaborate.

Usually with manual DI, I would have a parameterless constructor as shown in my code example, which calls into itself passing in a concrete class. Really there should be a composition root handling what is passed into the interface parameters and not a concrete defined for each class with a second constructor.

For small console apps etc this is manageable as Main is your composition root and where everything executes. However, on a asp.net mvc app for example, this becomes more complex. I was wondering what solutions if any other people have tried.

  • 2
    Um, what's the problem with passing new Something() as an argument to a constructor? – Zapadlo Nov 17 '17 at 13:33
  • And just in case (though I'm sure you're aware of it): blog.ploeh.dk/2014/06/10/pure-di and blog.ploeh.dk/2011/07/28/CompositionRoot – Zapadlo Nov 17 '17 at 13:34
  • "The below DI example is fine". I disagree. The public SomeClass:this(new Something()) {} constructor removes the guarantee that dependencies will be injected. – David Arno Nov 17 '17 at 13:39
  • Of course there is a way to keep concrete class creation in the composition root without using a container: you manually write the composition root. This is the key to pure DI (also known as "poor man's DI"). – David Arno Nov 17 '17 at 13:41
  • 2
    Possible duplicate of Dependency Injection with default Construction – Doc Brown Nov 17 '17 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.