I am confused about a few point in DI. Let me explain: Firstly, Does Dependency Injection has to follow Dependency Inversion Principle ? If so we can not inject concrete class instance as dependency. Because , this operation violates the DIP. Let'me ask my question over a example :
public class Client {
private Service service; // Service is concrete class !
Client(Service service) {this.service = service;}
}
So in this example, dependent and dependency are both concrete. Altough this violates DIP principle , Can we say this is Dependency Injection ?In my opininon , yes we can.Because DI is all object creation and these code fulfills the real duty and takes operation of creation object from dependent. But again at the same time it does not follow DIP. I am waiting for your thoughts :) Thanks in advance friends.
There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).
Depending on an interface is more flexible than depending on concrete classes. Object-oriented languages provide ways in which you can replace those abstractions with concrete implementations at runtime. You want to do this as much as possible since it is the best way to make your codebase flexible and reusable.
interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.
In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.
Does Dependency Injection has to follow Dependency Inversion Principle?
No it doesn't. Dependency Injection is just the practice of injecting dependencies into a component from the outside, instead of letting a component create or ask for those dependencies.
So although you can apply Dependency Injection without following the Dependency Inversion Principle, it is usually a good practice to follow the DIP, because DIP promotes loose coupling, which makes it easier to replace, decorate, intercept and mock dependencies, which increases testability, flexibility and maintainability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With