Dependency Injection – Acceptable Placement of Composition Root Using DI and IoC Containers

architectural-patternsdependency-injectiondesign-patternsioc-containersnet

I've read in several sources including Mark Seemann's 'Ploeh' blog about how the appropriate placement of the composition root of an IoC container is as close as possible to the entry point of an application.

In the .NET world, these applications seem to be commonly thought of as Web projects, WPF projects, console applications, things with a typical UI (read: not library projects).

Is it really going against this sage advice to place the composition root at the entry point of a library project, when it represents the logical entry point of a group of library projects, and the client of a project group such as this is someone else's work, whose author can't or won't add the composition root to their project (a UI project or yet another library project, even)?

I'm familiar with Ninject as an IoC container implementation, but I imagine many others work the same way in that they can scan for a module containing all the necessary binding configurations. This means I could put a binding module in its own library project to compile with my main library project's output, and if the client wanted to change the configuration (an unlikely scenario in my case), they could drop in a replacement dll to replace the library with the binding module.

This seems to avoid the most common clients having to deal with dependency injection and composition roots at all, and would make for the cleanest API for the library project group.

Yet this seems to fly in the face of conventional wisdom on the issue. Is it just that most of the advice out there makes the assumption that the developer has some coordination with the development of the UI project(s) as well, rather than my case, in which I'm just developing libraries for others to use?

Best Answer

Your binding module approach is the best solution. If the client is unlikely to change the configuration, the use of DI is questionable, for your library specifically.

If you wish to create a library for release to the public, you probably don't want clients to deal with the complexity or rigidity of the particular DI system you favor at the moment. Libraries are best when they are lower level components that can be used without lots of dependencies, or extensive training. Any DI system you select will change over time, and may become incompatible with client applications.

Related Topic