Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem Integrating Ninject v2 with Asp.net Webforms

I am trying to integrate Ninject v2 with my asp.net webforms project. I am running .NET Framework 4.0.

My global.asax inherits from Ninject.Web.NinjectHttpApplication. I have also added the CreateKernel method:

protected override IKernel CreateKernel()
{
  IKernel kernel = new StandardKernel();
  kernel.Bind<IUser>().To<User>();
  return kernel;
}

All my pages inherit from Ninject.Web.PageBase. I have also added the following httpmodule entry to my web.config:

<add name="NinjectHttpModule" type="Ninject.Web.NinjectHttpModule, Ninject.Web">

However when i run the application an InvalidOperationException is fired with the following:

"The type ASP.login_aspx requested an injection, but no kernel has been registered for the web application. Please ensure that your project defines a NinjectHttpApplication."

What am i doing wrong?

Kind Regards

Lee

like image 285
Lee Avatar asked May 21 '11 09:05

Lee


2 Answers

I had the same error in my ASP.NET 4.0 Webforms application. I fixed that by using sole 'Global.asax' file with code, instead of 'Global.asax' + 'Global.asax.cs' code behind. E.g. you can use this standalone 'Global.asax' file:

<%@ Application Language="C#" Inherits="Ninject.Web.NinjectHttpApplication" %>
<%@ Import Namespace="Ninject" %>

<script runat="server">
    protected override IKernel CreateKernel() {
        var kernel = new StandardKernel();
        kernel.Bind<IUser>().To<User>();
        return kernel;
    }
</script>

Also I never added any httpmodules to web.config, and it worked just fine!

like image 79
mikhail-t Avatar answered Oct 02 '22 00:10

mikhail-t


When you create a new web application, the Global.asax.cs file is filled with empty methods:

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
    }

The NinjectHttpApplication also implements these methods, but the empty methods in the generated Global.asax.cs never call the methods on NinjectHttpApplication. To solve this, remove the empty methods or add a call to the base method:

    void Application_Start(object sender, EventArgs e)
    {
        base.Application_Start();
    }
like image 31
Sjoerd Avatar answered Oct 02 '22 01:10

Sjoerd