简体   繁体   中英

Is it necessary to inject everything with Dagger 2?

I am new to Dagger. I have a confusion about what to and what not to inject with dagger. I know that it is necessary to inject Android Framework classes and my classes using Dagger but is it really necessary to inject even basic Java classes like String, StringBuilder etc using dagger or not.

 public String create(Context context) // Creating Simple objects in the method itself
{
 StringBuilder builder=new StringBuilder();
    ....
   return builder.toString();
}


public String create(Context context,StringBuilder builder) // Injecting everything
 {
....
return builder.toString();
}

You don't have to inject anything. You can create anything you like in the method. Inside the method is just plain old Java code.

Only inject something as a parameter when the thing you are creating in that method doesn't care about the specific value, but just needs a value.

The thing about injecting common classes is that you need to qualify them: this String you are injecting here isn't necessarily the same as that String you are injecting there. So you need some way to disambiguate them, such as annotations.

But if you are injecting everything as a matter of course, you will end up with an awful lot of annotations. Sometimes you do want to do this; sometimes not. It's something you get a feel of as you write more code.

Put a different way, the important part of injection is that it lets you manage the state of your objects (including lifecycle, if you want that).

So if you have a class with no state (eg a Util class that provides some stateless functions), you should never inject that.

If your StringBuilder class doesn't need to share state (ie use the same StringBuilder across two objects), then you don't need to inject it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM