Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject: Can modules be loaded that are declared as internal

Tags:

ninject

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

I have tried configuring InternalVisibleTo for the Ninject assembly, but this does not help.

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

like image 342
Tim Lloyd Avatar asked Jun 23 '11 13:06

Tim Lloyd


1 Answers

Internally KernalBase.Load(IEnumerable<Assembly assemblies) uses the GetExportedTypes() which only returns public types.

However, you could 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 could do the following.

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

This solution has not been tested though.

like image 50
mrydengren Avatar answered Nov 23 '22 21:11

mrydengren