There is a certain IEngine interface that is implemented in the DieselEngine and GasolineEngine classes. DieselEngine to make the Car class use this implementation? I understand that this should be done through the designer? Should a constructor accept a link to an interface or a class that implemented this interface?
Made through property. In the Main method I wrote the following

 Car car = new Car(_engine:new GasolineEngine()); car.engine.Speak(); Console.ReadLine(); 
  • It is enough to make the public IEngine engine{get;set;} property and set it, for example, in the constructor or after it. public Car(IEngine _engine) {engine = _engine;} - Dmitry Chistik
  • As you wish. Through property, through the designer, the link to the interface, the link to a specific class, somehow. - VladD
  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha

1 answer 1

In your case, IEngine is a dependency for Car . The main modes of transmission (or implementation ) dependencies are as follows:

  • Through the constructor. It is used in cases when dependencies are mandatory and the default implementation is not used.

     private readonly IEngine _engine; public Car(IEngine engine) { _engine = engine; } 
  • Through the property. Used when the default implementation is used. For example, all cars come with gasoline engines, but some may have diesel engines:

     public IEngine Engine { get; set; }; public Car() { Engine = new GasolineEngine(); } ... var car = new Car() { Engine = new DieselEngine() }; 
  • Through the parameters of the method. Used when dependency is only needed for a very limited number of methods in a class.

In your case, I think you should use dependency injection through the constructor.

At the same time, dependencies are usually passed through the interface - especially if there are several implementations. According to the principle of dependency injection, the details should depend on abstractions. Those. the car should depend on the general principles of engine functioning, and not on the details of how it functions.

  • you have readonly IEngine _engine; and you change it _engine = engine; Is this an exception? - Dmitri Chistik
  • 2
    @ Dmitry Chistik no . - andreycha
  • @Dmitry Chistik, in the constructor you can - Grundy