How to: Load Modules that Depend On a Module using Prism-v2

Today in the Prism forum this question presented an interesting scenario. If I create a module that is loaded on demand and other modules depend on it: how do I load them using Directory Lookup module enumeration?

This scenario could be used to develop new modules without changing the code of the one they depend on and simply store them in a folder so they get loaded.

As Julian Dominguez quickly explained there is a simple way to do this with Prism-v2:

[Module (ModuleName="IndependentModule", OnDemand = true)]
  public class IndependentModule :IModule
  {
      private readonly IModuleCatalog catalog;
      private readonly IModuleManager moduleManager;
      //Your code here

      public IndependentModule(IModuleManager moduleManager, IModuleCatalog catalog)
      {
          this.moduleManager = moduleManager;
          this.catalog = catalog;
          //Your code here
      }

      public void Initialize()
      {
          //Your code here                                                              

          var dependentModules = this.catalog.Modules.Where
              (m => DependsOnModule(m.DependsOn, "IndependentModule")).Select(m => m.ModuleName);
          foreach (string dependentModule in dependentModules)
          {
              moduleManager.LoadModule(dependentModule);
          }
      }

      private static bool DependsOnModule(IEnumerable<string> dependencies, string independent)
      {
          if (dependencies == null)
              return false;

          return dependencies.Contains(dependant);
      }
  }

Now if any modules in the directory depend on this module, they will automatically get loaded after this module is.

I hope you can find a good use for this.