1

How do we manage dependency injection in class libraries? Given the following class structure, we would like to inject an instance of Bar into Foo, and we would rather not make this the client's responsibility.

namespace MyLibrary {

    export class Foo {

        private readonly bar: Internal.Bar;

        constructor(bar: Internal.Bar) {
            this.bar = bar;
        }
    }
}

namespace Internal { 

    export class Bar { }
}

If there were a framework that managed dependency injection, then we would rely on that framework to provide an instance of Bar. If there were a main method, then we would new up all the dependencies there. In the case of a class library, though, where do we instantiate Bar?

In other words, where do we put the composition root of a class library?

1
  • 2
    Presumably Foo, if clients of your library don't understand Bar. If you want to inject Bar into Foo then you can provide a factory method for clients to use that instantiates both.
    – user253751
    Apr 26, 2017 at 5:15

1 Answer 1

1

The composition root would be anywhere you started using the classes in your library from the calling application through dependency injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.