Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for dependency injection

I am creating a new project in ASP.net using MVC 4.

I want to setup dependency injection using Ninject. But before I proceed what are the best practices when setting up dependency injection?

Currently I have a binder class setup within the webproject which will reference data projects within the solution.

The binder class is as shown below:

 Public static class Binder
{
    static Ninject.IKernel _kernel;

    static Binder()
    {
        _kernel = new Ninject.StandardKernel();

        _kernel.Bind<IConfig>().To<AppSettingsConfig>();
        _kernel.Bind<IDocuments>().To<DocumentsClass.Documents>();

    }

    public static T GetImplementation<T>()
    {
        return _kernel.Get<T>();
    }

}

Then within my controller i use the GetImplementation method to use the exact require dependency rather than registering all on application startup.

Example code from controller:

Public ActionResult Get (int id)
{
    var repository = Binder.GetImplementation<IDocuments>();

    // do some stuff with the repository here
}

Not sure if this would be a good approach? Any advice would be good.

like image 319
tjhack Avatar asked Jan 03 '13 11:01

tjhack


2 Answers

What you have now is an example of the Service Locator anti-pattern. Google for more details as it has been discussed many times.

In short, rather than relying on the service locator

public class SomeController 
{
  public ActionResult Get (int id)
  {
      var repository = Binder.GetImplementation<IDocuments>();

      // do some stuff with the repository here
  }
}

you should have your service injected into the client class (rely on constructor injection)

public class SomeController 
{
  private IDocuments documentService { get; set; }      

  public SomeController( IDocuments documentService ) 
  {
    this.documentService = documentService;
  } 

  public ActionResult Get (int id)
  {
      var repository = documentService; 

      // do some stuff with the repository here
  }
}

In this specific case, you could set up your controller factory to use your IoC container to resolve your controllers.

like image 72
Wiktor Zychla Avatar answered Oct 08 '22 07:10

Wiktor Zychla


Best practice for Ninject is to use the MVC extension for Ninject: https://github.com/ninject/ninject.web.mvc/wiki/MVC3

like image 41
Remo Gloor Avatar answered Oct 08 '22 06:10

Remo Gloor