mercredi 27 février 2019

DI & MVC: What's the point of dependency injection in controllers?

Short ver

Sometimes I see a piece of code where a dependency is injected into the constructor of a controller, but what advantage does it offer?

Long ver

Let's assume that you're seeing code like the following one.

//ASP.NET
public class SampleController : Controller 
{
    private IDependency dependency;

    public SampleController(IDependency dependency) 
    {
        this.dependency = dependency;
    }
}

Or, if you prefer PHP, let's have a look at the following one

//PHP with Laravel
namespace App\Http\Controllers;

class SampleController extends Controller
{
    private $dependency;

    public function __construct(Dependency $dependency)
    {
        $this->dependency = $dependency;
    }
}

As far as I know, Dependency Injection is meant to decouple a client from its dependency, so that...

  1. the client can use different dependencies at run time (with a setter method)
  2. updating the dependency class is less likely to force you to update the client too

...etc.

However, controllers are not instantiated,

$service = new Service();
$controller = new Controller($service);
//you don't do such a thing, do you?

....nor do controllers use setter functions (usually).

Nonetheless, I still see this approach on the internet, including ASP.NET's doc.

Is it really beneficial to inject a dependency into a controller rather than instantiating a class within the constructor with the new keyword? (If so, how does this approach improve your code?)

Aucun commentaire:

Enregistrer un commentaire