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

我与影子孤独终老i 提交于 2019-12-10 13:23:37

问题


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?


回答1:


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);



回答2:


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();



来源:https://stackoverflow.com/questions/23628290/ninject-scan-assemblies-for-matching-interfaces-and-load-as-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!