Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Dependency Resolver or Ninject MVC plugin?

In MVC 3 they added a Dependency Resolver what I been using. While answering someone question someone commented on you should use the Ninject MVC 3 plugin.

So my question is why use it over the built in one? If it is the way to go how do you setup it up?

Question

So above is the link to the question that I answered.

like image 492
chobo2 Avatar asked Mar 01 '11 20:03

chobo2


1 Answers

ASP.NET MVC 3 provides a dependency injection service which will hook into whatever dependency resolver you choose to implement. The Ninject MVC 3 plugin is very simple in its function because all it must do is implement the type-resolution methods defined in System.Web.Mvc.IDependencyResolver and call the appropriate Ninject methods to return a requested type.

Whether you choose to use your own IDependencyResolver and map it to Ninject (or any other dependency injection framework), or you choose to use the freely available Ninject MVC 3 plugin, is mostly a trivial distinction.

Here's a fully-functional example of what a hand-rolled, Ninject-compatible IDependencyResolver might look like. The Ninject MVC 3 plugin would be fundamentally very similar:

public class NinjectDependencyResolver : IDependencyResolver
{
    private readonly IKernel _kernel;

    public NinjectDependencyResolver(IKernel kernel) {
        _kernel = kernel;
    }

    public object GetService(Type serviceType) {
        return _kernel.TryGet(serviceType, new IParameter[0]);
    }

    public IEnumerable<object> GetServices(Type serviceType) {
        return _kernel.GetAll(serviceType, new IParameter[0]);
    }
}

The key point here is that ASP.NET MVC does not provide a full-fledged dependency injection framework; it provides only the layer needed to retrieve a required type instance by way of an IoC container (i.e. Ninject) at specific points throughout the ASP.NET MVC request pipeline (Controller resolution, View resolution, etc).

Note: if any of the terminology I used isn't quite accurate, please inform me.

like image 114
Nathan Taylor Avatar answered Nov 07 '22 05:11

Nathan Taylor