Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understand your concerns correctly, you're trying to prevent any class that needs to instantiate a new Car object from having to inject all those dependencies manually.</p> <p>I've used a couple patterns to do this. In languages with constructor chaining, I've specified a default constructor that injects the concrete types into another, dependency-injected constructor. I think this is a pretty standard manual DI technique.</p> <p>Another approach I've used, which allows some looser coupling, is to create a factory object that will configure the DI'ed object with the appropriate dependencies. Then I inject this factory into any object that needs to "new" up some Cars at runtime; this allows you to inject completely faked Car implementations during your tests, too.</p> <p>And there's always the setter-injection approach. The object would have reasonable defaults for its properties, which could be replaced with test-doubles as needed. I do prefer constructor-injection, though.</p> <hr> <p>Edit to show a code example:</p> <pre><code>interface ICar { float getSpeed(); } interface ICarFactory { ICar CreateCar(); } class Car : ICar { private Engine _engine; private float _currentGearRatio; public constructor(Engine engine, float gearRatio){ _engine = engine; _currentGearRatio = gearRatio; } public float getSpeed() { return return _engine.getRpm*_currentGearRatio; } } class CarFactory : ICarFactory { public ICar CreateCar() { ...inject real dependencies... } } </code></pre> <p>And then consumer classes just interact with it through the interface, completely hiding any constructors.</p> <pre><code>class CarUser { private ICarFactory _factory; public constructor(ICarFactory factory) { ... } void do_something_with_speed(){ ICar car = _factory.CreateCar(); float speed = car.getSpeed(); //...do something else... } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload