asp.net-mvc-3ninject-2property-injection

Accessing a base class property that is defined with Property Injection in the base class's constructor


I've read through everything on the ninject wiki and lots of posts and still don't understand how to set up injection so that I can reference this property. I want to be able to reference the property in the base class constructor to ultimately set a common ViewBag property when any controller is created. It seems like implementing the iInitializable interface would be the right approach but again just not sure how to do this. Also, I chose not to inject IMyService in the base class constructor to simplify the coding of the derived classes.

simplifed version of my latest attempt at code:

public class AppController : Controller 
{

    [Inject]
    public IMyService myService{get; set;}

    public AppController()
    {
       //I want to do this, but myService is null
       //ViewBag.DefaultName = myService.Name;
    }

}

public class DashboardController : AppController
{
    public ActionResult Index()
    {
        //myService is accessible, so injection works
        return View();
    }
 }

Solution

  • Properties are injected after the constructor is called meaning that you need to use either constructor injection or access them after the object has been instantiated. You could make your controller implement IInitializable:

    public class AppController : Controller, IInitializable
    {
        [Inject]
        public IMyService MyService { get; set; }
    
        public void Initialize()
        {
            ViewBag.DefaultName = MyService.Name;
        }
    }
    
    public class DashboardController : AppController
    {
        public ActionResult Index()
        {
            return View();
        }
    }