Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject -> Scan assemblies for matching interfaces and load as modules

In earlier versions of Ninject.Extensions.Conventions, it was pretty easy to scan a directory for assemblies, filter classes by interface and then load all containing ninject modules.

kernel.Scan(scanner =>
    scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
    scanner.AutoLoadModules();
    scanner.WhereTypeInheritsFrom<IPlugin>());

public class MyPlugin : NinjectModule, IPlugin {

     public override void Load() {
          Bind<IRepositoryFromPluginHost>().To<MyPluginImpl>().Named("special");
     }
}

However, after I updated lately to the newest release, everything seems gone and I'm unable to

  1. Auto load modules
  2. Filter types by interfaces

Does anybody have a solution for this?

like image 802
Acrotygma Avatar asked May 13 '14 10:05

Acrotygma


2 Answers

There's still the https://github.com/ninject/ninject.extensions.conventions extension. However, the interface has changed, to something along the lines of:

kernel.Bind(x =>
{
    x.FromAssembliesInPath("somepath")
     .IncludingNonePublicTypes()
     .SelectAllClasses()
     .InheritedFrom<IPlugin>()
     .BindDefaultInterface() // Binds the default interface to them;
});

Update: How about you bind all IPlugin to IPlugin using the conventions extension (as above), and then do:

var plugins = IResolutionRoot.GetAll<IPlugin>();
kernel.Load(plugins);
like image 131
BatteryBackupUnit Avatar answered Sep 21 '22 03:09

BatteryBackupUnit


Maybe the hard way, but something like this will get you a list of types that are derived from NinjectModule.

var assemblies = AppDomain.CurrentDomain.GetAssemblies(); 
List<Type> types = new List<Type>();
foreach (var assembly in assemblies) 
{
    types.AddRange(GetModules(assembly)); 
}


    IEnumerable<Type> GetModules(Assembly assembly)
    {
         assembly.GetTypes()
              .Where(t => t.BaseType == typeof(NinjectModule));       
    }

To load your module try this.

(Activator.CreateInstance(type) as NinjectModule).Load();

like image 23
Eric Avatar answered Sep 18 '22 03:09

Eric