I've read various other question here on the argument, most notably
Dependency Inject (DI) “friendly” library
Ioc/DI - Why do I have to reference all layers/assemblies in entry application?
and this article (and other various material).
However it's not clear to me where to place composition root in library (DLL) .NET project. The project does not belong to any specific type mentioned in the article. In desktop, console or even web application this point is instead clearly defined.
My current approach is to wrap the container, register types and re-expose the Resolve method:
class DefaultBootstrapper : IBootstrapper {
public Bootstrapper() {
_container = new XXXContainer();
RegisterTypes(_container);
}
public T Resolve<T>() where T : class {
return _container.Resolve<T>();
}
// + other _container.Resolve() overloads
private readonly XXXContainer _container;
}
Then I prevent library consumers to create root instances of the library (e.g. defining internal constructors) and hence forcing the use of a singleton factory:
class XYZFactory {
static XYZFactory() {}
private XYZFactory(IBootstrapper bootstrapper) {
_bootstrapper = bootstrapper;
}
public static XYZFactory Instance {
get { return Singleton; }
}
public ABCType CreateABCType(string param1) {
return _bootstrapper.Resolve<ABCType>(param1, _bootstrapper.Resolve<Dependency1>);
}
private static readonly XYZFactory Singleton = XYZFactory(new DefaultBootstrapper);
private readonly IBootstrapper _bootstrapper;
}
The question is, there's a better approach or a better pattern to employ for locate the composition root in a library project?