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?
Foo
, if clients of your library don't understandBar
. If you want to injectBar
intoFoo
then you can provide a factory method for clients to use that instantiates both.