I\'m developing a MVC5 project on Visual Studio 2017 Version 15.4. I\'m getting unexpected result here what I never faced before. I\'ve installed Ninject.MVC5
packa
After lot of search and tests, I've got the exact solution, where I faced error while system was trying to create multiple instances at a time with the previous answer. Here I needed to create NinjectWebCommon
class only without inheriting NinjectHttpApplication
.
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
///
/// Starts the application
///
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
///
/// Stops the application.
///
public static void Stop()
{
bootstrapper.ShutDown();
}
///
/// Creates the kernel that will manage your application.
///
/// The created kernel.
///
/// Creates the kernel that will manage your application.
///
/// The created kernel.
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
///
/// Load your modules or register your services here!
///
/// The kernel.
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new INinjectModule[]
{
new Module()
});
}
}
But here is a problem with parameterized constructor. To avoid this issue I added a method to create Concrete Instance. So here is the updated code..
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
///
/// Starts the application
///
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
///
/// Stops the application.
///
public static void Stop()
{
bootstrapper.ShutDown();
}
///
/// Creates the kernel that will manage your application.
///
/// The created kernel.
///
/// Creates the kernel that will manage your application.
///
/// The created kernel.
private static IKernel CreateKernel()
{
return Container;
}
public static T GetConcreteInstance()
{
object instance = Container.TryGet();
if (instance != null)
return (T)instance;
throw new InvalidOperationException(string.Format("Unable to create an instance of {0}", typeof(T).FullName));
}
public static IKernel _container;
private static IKernel Container
{
get
{
if (_container == null)
{
_container = new StandardKernel();
_container.Bind>().ToMethod(ctx => () => new Bootstrapper().Kernel);
_container.Bind().To();
RegisterServices(_container);
}
return _container;
}
}
///
/// Load your modules or register your services here!
///
/// The kernel.
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new INinjectModule[]
{
new Module()
});
}
}