0

I'm using Ninject.Web.Common and I really like Ninject so far. I'm not used to dependency injection yet so I've got a pretty lame question I can't however google and answer to so far. Suppose I have a Message Handler which depends on my IUnitOfWork implementation. I need to construct an instance of my handler to add it to Web API config. I've managed to achieve this using the following code:

var resolver = GlobalConfiguration.Configuration.DependencyResolver;
            config.MessageHandlers.Add((myproject.Filters.ApiAuthHandler)resolver.GetService(typeof(myproject.Filters.ApiAuthHandler)));

I really dislike typing this kind of stuff so I'm wondering if I'm doing it right. What's the common way of constructing dependent objects manually?

devmiles.com
  • 9,895
  • 5
  • 31
  • 47

1 Answers1

0

Well I use dependency injection in real world projects only half a year ago, so I'm a pretty new to this stuff. I would really recommend the Dependency Injection in .NET book, where all the concepts are described pretty well and I learned a lot from it.

So far for me what worked the best is overwriting the default controller factory like this:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel _kernel;

    public NinjectControllerFactory()
    {
        _kernel= new StandardKernel();
        ConfigureBindings();
    }

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

    private void ConfigureBindings()
    {
        _kernel.Bind<IUnitOfWork>().To<MessageHandler>();
    }
}

And in the Global.asax in the Application_Start function you just have to add this line:

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

This approach is called the composition root pattern and considered the "good" way for dependency injection.

What I would recommend as well that if you have multiple endpoints like services and other workers as well you should create an Application.CompositionRoot project and handle there the different binding configuration for the different endpoints for your application.

Márk Gergely Dolinka
  • 1,430
  • 2
  • 11
  • 22