Search code examples
asp.net-mvc-3webformsninjecthttpmodule

How can you inject objects into non-controller objects using Ninject 3.0 with ASP.NET MVC3


I have an MVC3 project that I am using Ninject to inject an Entity Framework context into. I am using the Ninject package (3.0.0.15), Ninject.MVC3 (3.0.0.6), and Ninject.Web.Common (3.0.0.7). Everything is working really great, except when I try to inject into a WebForms code behind file. I am assuming that this is because I don't have something wired in correctly, but am not sure at how to wire it in. Ninject is also not working in files that Razor instantiates.

Here is my code for my Code Behind:

[Inject]
public IDbContext DataContext { get; set; }

The Context property comes out null every time. It worked just fine until I updated to Ninject 3.0.

My start method is as follows:

public static void Start()
{
    DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
    DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
    Bootstrapper.Initialize(CreateKernel);
}

Any ideas on how to make Ninject inject the DataContext into the WebForm and into classes instantiated by Razor?


Solution

  • For this to work you need to install the Ninject.Web NuGet (the latest version at the time of this writing is 3.0.0.5) and then have your webform derive from Ninject.Web.PageBase instead of System.Web.UI.Page:

    public partial class WebForm1 : Ninject.Web.PageBase
    {
        [Inject]
        public IDbContext Ctx { get; set; }
    
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
    

    Also notice that I used Ctx as property name because there's already a property called Context on the System.Web.UI.Page class that you are hiding (you should have gotten a compile time warning).