5
votes

I tried the following solution found in How can I implement Ninject or DI on asp.net Web Forms? (Jason's answer)

  1. Create a new ASP.NET WebForms project
  2. Use NuGet to add the Ninject.Web lib (which will also bring down the Ninject.Web.Common and Ninject libs)
  3. Register your custom bindings in App_Start / NinjectWebCommon.cs / RegisterServices method
  4. Use attribute injection on your pages

Works great in ASP.NET web applications.

The problem is I want to use Ninject for DI in an ASP.NET web site, not a web application.

I registered custom bindings in NinjectWebCommon / RegisterServices:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ITestRepository>().To<TestRepository>();
}

In a web page I inject it:

public partial class _Default : System.Web.UI.Page
{
    [Inject]
    public ITestRepository _repository { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        System.Diagnostics.Trace.WriteLine(_repository.ExecuteOperation());
    }
}

It always throws a null reference exception and the breakpoint inside NinjectWebCommon.cs is never reached - unlike in a web application.

What else should be done to make Ninject 3 work in a web site?

2
Note that the breakpoint is hit because the debugger attaches too late. If you write Debugger.Break() before kernel.Bind<...>... it will hit that line.nebffa

2 Answers

10
votes

My first advice to you is...

Don't use ASP.NET Web Sites. Forget they exist. Avoid them at all costs. They are an anachronistic throwback to days of yore that are only still here for legacy reasons.

My second piece of advice would be...

If you insist on continuing to use a Web Site project, invest heavily in headache medicine, as you will need it.

My third piece of advice would be...

See First Advice.

My fourth piece of advice would be...

If you have absolutely no control over whether or not it's a Web Site project or not, then just give up on the idea of using Ninject or any other DI container. Website projects inherit from a different set of base classes than Web Application sites. You won't get it to work the same way, and you will probably spend way too much time trying to make it fit.

EDIT:

Basically, the code model works very differently between Web Sites and Web Applications. You need only look no further than the fact that Web Site apps don't have namespaces while Web Application apps do. This should tell you how vastly different these are.

I'm not entirely sure the activation process even works the same in both.

However, having said all that. There is a glaring problem with your code. Your page derives from System.Web.UI.Page rather than Ninject.Web.PageBase

1
votes

According to the other question you linked to, you need your page to inherit from Ninject.Web.PageBase. It appears your page is inheriting from System.Web.UI.Page, which doesn't know how to inject your dependent repository.