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?
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With