7

I am at a loss of what to do with the multitude of documentation available through google in .net as regards using Ninject with asp.net mvc 4

First of all, i want to know if Controller factories are neccessary in asp.net.

Also, is constructor injection really the only way we can do dependency injection with MVC 4 because property injection and method injection does not seem to work when i use them with my controllers

Paul Plato
  • 1,471
  • 6
  • 28
  • 36

2 Answers2

9

I am not an expert on Ninject but as far as i know, i am only using it to link my DataSource Interface and my EfDb Class to the rest of my application.

If you need a good book that has a Real Application built around Ninject try: Pro ASP.NET MVC 3 Framework, Third Edition

or

Pro Asp.Net Mvc 4

There are very few lines of code i am usually concerned with

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
        AddBindings();
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null
                   ? null
                   : (IController) ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<IDataSource>().To<EfDb>();
    }
}

Then register your NinjectControllerFactory in Global.asax.cs with:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

As you can see, this class use Method Injection using private void AddBindings(). This makes it very easy if you are following Test Driven Development (TDD)

Komengem
  • 3,662
  • 7
  • 33
  • 57
  • But i read somewhere that if u your application inherited from NinjectHttpApplication and override the appropriate methods, controllers will automatically have dependencies statisfied via IOC Container. – Paul Plato Mar 11 '13 at 15:54
  • @PeterEdike Everyone has they own way of writing code, this game is all about picking up a style that works and improving it on the way. I would suggest you read one of those books i mentioned. – Komengem Mar 11 '13 at 19:20
  • I dont know much about this but this code work fine. – Prageeth godage Mar 06 '14 at 19:19
2

See the documentation here: https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-controllers, "The only thing that has to be done is to configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding."

NInject will automagically set up your controller dependencies (provided it has a binding for those types).

stevef4000
  • 98
  • 1
  • 6