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.
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