Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 262
Mesut Dogan Avatar asked Nov 26 '15 10:11

Mesut Dogan


People also ask

What are the three types of dependency injection?

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

Why is it beneficial for client code to depend on an interface rather than concrete classes?

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.

Does dependency injection need interface?

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.

What is dependency injection interface?

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.


1 Answers

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.

like image 171
Steven Avatar answered Sep 18 '22 10:09

Steven