Search code examples
asp.net-mvc-3ninjectninject-2

Property Injection without attributes using Ninject in an abstract base controller in MVC3


I have the following code:

public abstract class BaseController : Controller
{
    public IUserService UserService { get; set; }
}

All my controllers inherit from this base controller. I started out by configuring it in Ninject using the following code:

kernel.Bind<BaseController>()
      .ToSelf()
      .WithPropertyValue("UserService", x => x.Kernel.GetService(typeof(IUserService)));

This did not work. I assume it is because of the fact that the BaseController is an abstract class (please confirm my assumption). So I moved on to modify the configuration to:

kernel.Bind<HomeController>()
      .ToSelf()
      .WithPropertyValue("UserService", x => x.Kernel.GetService(typeof(IUserService)));

This does work. The minor downside is that I now have to configure every controller the same way.

Since I also have DependencyResolver setup in my ASP.NET MVC 3 project I could also remove the above Ninject configuration and modify my base controller to look like:

    public IUserService UserService
    {
        get
        {
            return DependencyResolver.Current.GetService<IUserService>();
        }
    }

Is there any benefit to using the fluent configuration as opposed to using the DependencyResolver approach? Is one better than the other? Which approach would be considered a better practice?

It is worth mentioning that I did not want to do constructor injection in my base controller.


Solution

  • A better practice in MVC it is to use constructor injection over property injection. Why did you make your choice like this ?

    Using Constructor Injection you states that all dependencies in constructor are necessary for the class to do its job.

    Property injection means that the dependencies are optional or that there are the local defaults implementations, so all will work even if you don't provide necessary implementations yourself.

    You should really know what you're doing using Property injection or you have no other choice, so the safer approach is to rely on constructor injection.

    Now I'll give you my point of view. Other may have other opinions.

    DependencyResolver was introduced in MVC 3 for "convenient" service location but for me it's a regular Service locator which for me is also an anti-pattern http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx. I don't use it because I don't like it and there is no benefit in using it. I prefer to user my controller factory like before and pass the dependencies through constructor.

    More the IDependencyResolver has somme issues with some IoC containers (I don't know if it's the case with Ninject). You can read more here : http://mikehadlow.blogspot.com/2011/02/mvc-30-idependencyresolver-interface-is.html