3

I am building an ASP.NET MVC5 web application, using Ninject.MVC5 for DI. I'm trying to move the NinjectWebCommon class into a separate class-library project. I was able to do this successfully by using the following code:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    try
    {
        // Uncomment to move this file to a separate DLL
        kernel.Load("MyWebApp.dll");
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }
    catch
    {
        kernel.Dispose();
        throw;
    }
}

In the above code, MyWebApp.dll is the filename of the main web application assembly. This works, but requires me to hard-code a reference to the web application DLL. I read in the official documentation that the following could can be used to automatically load all DLLs in a solution that has been separated in this fashion:

kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

However, if I use this code instead of the hard-coded reference, I receive the following exception (caught and re-thrown at the throw line above):

An exception of type 'System.NotSupportedException' occurred in
MyWebApp.Infrastructure.dll and wasn't handled before a managed/native boundary

Additional information: Error loading module 'Ninject.Web.Mvc.MvcModule' of
type MvcModule

Can anyone provide some information on what is happening here, and how to prevent this exception from occurring while avoiding hardcoded references to other assemblies?

Brett Wolfington
  • 6,587
  • 4
  • 32
  • 51
  • `AppDomain.CurrentDomain` contains only assemblies which were already loaded into domain - in general case, that is not all the DLLs in the \bin folder. If you can reference `MyWebApp.dll`, then you can just use `typeof(SomeClassInsideMyWebApp).Assembly`. – Lanorkin Oct 12 '14 at 10:34

1 Answers1

5

When you create your Kernel, you need to make sure that the setting LoadExtensions is set to false.

According to the documentation :

LoadExtensions: Gets or sets a value indicating whether the kernel should automatically load extensions at startup.

The following line:

var kernel = new StandardKernel();

... should become this:

var kernel = new StandardKernel(new NinjectSettings() { LoadExtensions = false });
Maxime
  • 8,645
  • 5
  • 50
  • 53