[ASP.NET MVC] Dependency Resolver with Ninject

DI(Dependency Injection) becomes the must-have patterns in any applications. MVC does work with any DI Containers such as Ninjet or Unity. MVC also provides the “Dependency Resolver” feature to make DI much easier.

1. IDependencyResolver Interface

The “System.Web.Mvc.IDependencyResolver” interface defines the methods that simplify dependency resolution

public interface IDependencyResolver
{
  object GetService(Type serviceType);
  IEnumerable<object> GetServices(Type serviceType);
}

 

2. Ninject Dependency Resolver

Ninject lets us to create a custom Dependency Resolver very easily.

public class NinjectDependecyResolver : IDependencyResolver
{
  IKernel kernal;

  public NinjectDependecyResolver()
  {
    kernal = new StandardKernel();
    AddBindings();
  }

  public object GetService(Type serviceType)
  {
    return kernal.TryGet(serviceType);
  }

  public IEnumerable<object> GetServices(Type serviceType)
  {
    return kernal.GetAll(serviceType);
  }

  void AddBindings()
  {
    kernal.Bind<ICalculator>().To<EngineeringCalculator>();
    ...
  }
}

 

3. Registering Dependency Resolver

Once you have a custom Dependency Resolver, you need to let MVC framework to use it.

public class DependencyResolver
{
  public static void SetResolver(IDependencyResolver resolver);
}

You can call the static “DependencyResolver.SetResolver()” method in the “Application_Start()” method.

protected void Application_Start()
{
  ...

  DependencyResolver.SetResolver(new NinjectDependecyResolver());
}

That’s all.

 

One thought on “[ASP.NET MVC] Dependency Resolver with Ninject

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s