Mesut Dogan
Mesut Dogan

Reputation: 592

Dependency Injection Interface Vs Concrete classes?

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.

Upvotes: 5

Views: 1089

Answers (1)

Steven
Steven

Reputation: 172616

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.

Upvotes: 9

Related Questions