问题
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
- Auto load modules
- 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