Search code examples
c#autofacautofac-module

Should Autofac modules register their own dependent modules?


Consider I have an app that uses three libraries, lib1, lib2 and lib3. In each of the libraries I have implemented a Module that registers the dependencies that are implemented in that library.

Some of these implementations have their own dependencies, for instance, lib2 and lib3 might both need some implementations that exist in lib1.

My question is, do I let the module in lib2 and lib3 register the module in lib1 as part of their Load implementation? Is this going to register that module twice if my app registers the modules of lib2 and lib3?

Or do I refrain from letting a module register another module, leaving it up to the app with the drawback that some registrations might be missing at startup?


Solution

  • I won't recommend doing registrations inside your libraries. In most case you should have one composition root that will compose all your application.

    A Composition Root is a (preferably) unique location in an application where modules are composed together.

    This concept is explained here composition root.

    By the way, if your register a module multiple time, Autofac will register component multipe time. If you must have module inside your library you should only create module that register component of the library.