Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I inject every and any class or specific classes?

I just started getting into DI(dependency injection) frameworks and I was wondering should I inject every and any class or specific classes? How would I know which classes you should inject and which you shouldn't?

A lot of the tutorials(Dagger 2, Hilt, etc) that I've found don't seem to talk about this or don't explain it very well.

I don't have any code examples cause I'm trying out things as I read along with tutorials. Just trying to get a feeling of things.

Explain it as if I was 4 year old :)

like image 201
Jcorretjer Avatar asked Oct 28 '25 04:10

Jcorretjer


1 Answers

My answer is no, you do not have to do that use dependency injection every time you need to create an object.

This is the intent of dependency injection according to Wikipedia

The intent behind dependency injection is to achieve separation of concerns of construction and use of objects. This can increase readability and code reuse.

So you should use dependency injection it would improve your code reuse and readability.

This article mentions some cases where you should use dependency injection to create objects

  1. You need to inject configuration data into one or more components.
  2. You need to inject the same dependency into multiple components.
  3. You need to inject different implementations of the same dependency.
  4. You need to inject the same implementation in different configurations.
  5. You need some of the services provided by the container.

Imagine that you have username and password fields in an app that you would use to capture a user's detail, you do not have to use dependency injection to create a User object from the details, you can just create it directly, its not something that would be reused across your application, there are other object creation patterns that you should look into like factory pattern, abstract factory pattern, builder pattern e.t.c.

like image 149
oziomajnr Avatar answered Oct 30 '25 19:10

oziomajnr