Ninject: modules declared as internal can load

Is it possible to configure Ninject to load modules that have been declared as internal ?

I tried to configure InternalVisibleTo to build Ninject, but that does not help.

I can, of course, make the modules public , but in fact they should be internal .

+6
source share
3 answers

Inside KernalBase.Load(IEnumerable<Assembly assemblies) , GetExportedTypes() , which returns only public types.

However, you can write your own NinjectModule Scanner.

 public static class NinjectModuleScanner { public static IEnumerable<INinjectModule> GetNinjectModules(IEnumerable<Assembly assemblies) { return assemblies.SelectMany(assembly => assembly.GetNinjectModules()); } } public static class AssemblyExtensions { public static IEnumerable<INinjectModule> GetNinjectModules(this Assembly assembly) { return assembly.GetTypes() .Where(IsLoadableModule) .Select(type => Activator.CreateInstance(type) as INinjectModule); } private static bool IsLoadableModule(Type type) { return typeof(INinjectModule).IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface && type.GetConstructor(Type.EmptyTypes) != null; } } 

Then you can do the following.

 var modules = NinjectModuleScanner.GetNinjectModules(assemblies).ToArray(); var kernel = new StandardKernel(); 

This solution has not yet been tested.

+7
source

You can configure Ninject to introduce inner classes using the InjectNonPublic property of the InjectNonPublic class. You should pass it as an argument to the StandardKernel constructor:

 var settings = new NinjectSettings { InjectNonPublic = true }; kernel = new StandardKernel(settings); 
+4
source
 var kernel = new StandardKernel(); var modules = Assembly .GetExecutingAssembly() .DefinedTypes .Where(typeof(INinjectModule).IsAssignableFrom) .Select(Activator.CreateInstance) .Cast<INinjectModule>(); kernel.Load(modules); 
0
source

Source: https://habr.com/ru/post/891211/


All Articles