mason
mason

Reputation: 32693

Ninject not injecting service into Web Forms page

I've trying to use Ninject for DI in a combined ASP.NET Web Forms and MVC project. I installed the following packages (and their dependencies) via NuGet:

Ninject.MVC5 3.2.1.0

Ninject.Web 3.2.1.0

In ~/App_Start/NinjectWebCommon.cs I register services:

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

In MVC controllers, I use constructor injection to retrieve my ITermusRepository implementation:

public class Appraisal2013_2014FullController : Controller
{
    ITermusRepository repo { get; set; }

    public Appraisal2013_2014FullController(ITermusRepository Repo)
    {
        repo = Repo;
    }
}

MVC works great, I use the repo later in my action methods to successfully retrieve data. All is well there.

In Web Forms, I use attribute injection.

public partial class _2013_2014_TERMUS_PaperTermus : BasePage
{
    [Inject]
    ITermusRepository repo { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {               
            var appraisal = repo.LoadByTermusId<Termus2013_2014EndYear>(Request.QueryString["TERMUSID"]);
        }

}

However, repo.LoadByTermusId() call fails with a NullReferenceException because repo is null.

System.NullReferenceException: Object reference not set to an instance of an object.

Clearly Ninject is set up correctly at least for MVC. I don't understand why my implementation of ITermusRepository isn't getting injected into my Web Forms code behind. What can I do to get it to inject it properly?

I used Jason's answer from How can I implement Ninject or DI on asp.net Web Forms? as my pattern for getting this working. I don't want to use Joe's answer, as it requires modifying the base class of the global application class, pages, master pages, ASMX services, generic handlers etc. And that appears unnecessary in the current version of Ninject.

Upvotes: 0

Views: 1399

Answers (1)

mason
mason

Reputation: 32693

[Inject]
ITermusRepository repo { get; set; }

needed to be

[Inject]
public ITermusRepository repo { get; set; }

That fixed the problems with my .aspx Web Forms pages. But it wasn't injecting them into my .ashx generic handlers. Since I don't have many of those, I created a constructor in my handler class and retrieved the service from the kernel.

ITermusRepository repo { get; set;}

public GetPDF()
{
    var kernel = TERMUS.App_Start.NinjectWebCommon.CreateKernel();
    repo = kernel.Get<ITermusRepository>();
}

Upvotes: 1

Related Questions