Search code examples
asp.net-mvcninjectasp.net-mvc-4

Ninject Constructor injection and build problems


Inheriting from MVC Controller Class

public class BaseController  : Controller
{

    private ITenantRepository _repository;
    [Inject]
    public BaseController(ITenantRepository repository)
    {
        _repository = repository;
    }
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);
    }
}

can't build

BaseController' does not contain a constructor that takes 0 arguments

clearly I am missing something obvious.


Solution

  • In your child controllers make sure that you have defined a constructor with the same parameters as your base class:

    public class FooController: BaseController
    {
        public FooController(ITenantRepository repository): base(repository)
        {
        }
    
        ...
    }
    

    You need to do this because in the base class you have removed the parameterless constructor and replaced it with a custom one. So derived classes must also be removed from their parameterless constructor.

    Also note that the normal way of using Ninject with ASP.NET MVC is to set it up as the DependencyResolver at the top level of your app. The controllers should not use any container-specific attributes such as the [Inject] attribute you used as these tie your code to the dependency injection container you are using.

    Note as well that in addition to being bad practice from the preceding perspective, the [Inject] attribute on the constructor in your code has no material effect:

    • Nothing is going to step in and say 'Look, it's got an attribute, we better provide its dependencies'
    • If you do have Ninject configured as the DependencyResolver, it won't need the attribute as there's no ambiguity whatsoever as to what's needed to construct the controller
      • there's no default constructor
      • there's no competing constructor