How to properly create heirarchy of dependency in dagger 2 in Android - android

I have a couple of questions, since there is no decent documentation on Dagger 2. I am very new in programming, so the questions might be stupid
1) Is it ok to have only 1 component in application that consist of all modules.
2) It seems that you need to inject only from 1 component in the class or all of the components must provide all of the #inject objects.
3) For instance, if in my application I have 2 different objects in 2 modules of the same type but for different purposes and 1 singleton object for whole app.
How do I inject singleton object and one of my 2 different objects for the certain purpose. How Dagger will understand what exact object do I want.

Related

Android Kotlin object vs Dagger2 for singleton models

I saw this question, but it was from the point of testability.
In my case, I see Dagger as an additional complexity for code (create #Provides methods, inject methods, remember all the right annotations). Should I still use Dagger if I just want to inject singletons like SharedPrefUtils? Is it really faster for this case?
Dagger was not made for creating Singletons and if creating a singleton is the reason you want to add Dagger to your project, then its an overkill. Dagger is a dependency injection framework that helps make the process of providing and injecting dependencies easier in a complex project. The #Singleton would help you ensure that only a single instance of a class is created when satisfying your dependencies it is not an alternative to the Kotlin object, they could even be used together. So like other answers and comments suggest if you have a small project and you could use simple design patterns like Singleton, Factory, and Abstract factory pattern.
Dagger is a dependency injection framework. For very simple applications, you can go with manual injection which will save you time because dagger can be difficult to set up and work with from the beginning. However, if you are planning on a production application which has a very long life span and will contain multiple UIs and multiple classes, then you are definitely going to need a dependency injection framework or strategy along the line.
There is an alternative for Kotlin which is Koin. Koin works more like a Service Locator and is easier to set up than Dagger but I will prefer dagger because it has survived the test of time.
It is up to you whether you want to use automatic dependency injection or manual injection so in the end you weigh your options and see what best fits your use case.

What is dagger exactly, and how it works [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I know this may be not the correct way to ask question but after reading lot and lot I am still confused about daggers and how it works and why we should use it. Since its been used in my current working project. Please somebody give me little hint in simple words what is the purpose of dagger will be very helpful.
Dagger is a compile-time JSR-330 dependency injection framework based on Java annotations.
What is dependency injection?
Dependency injection (sometimes termed Inversion of Control or IoC) is based on the idea that a given class should not need to know how to create or provide the classes it depends on. Providing those dependencies should be the responsibility of the class's user (or a separate class or factory).
For example, let's say you have class A that depends on class B, that depends on classes C and D. (In real terms, that might be an Application, that depends on a BusinessLogicClass, that depends on a Calculator and a Database.) It could look like this:
class A {
private B b = new B();
}
class B {
private C c = new C();
private D d = new D();
}
...but at that point it would be really hard to use a different C or D (calculator or database), even your B (business logic class) should work with a variety of data sources, or if you need to replace any of those pieces for unit testing. Dependency injection, as a concept, says that you should be able to pass in dependencies into the classes when you create them.
A a = new A(new B(new C(), new D())); // Now you get an A, but can replace any part of it.
What is a dependency injection framework?
A dependency injection framework automatically creates factories for all of your classes, so you can create an A without worrying about its dependencies, or its dependencies' dependencies.
A a = new AFactory().getA(); // Equivalent to the above, but easier!
Dependency injection frameworks usually come with a language for you to specify mappings, often called bindings, which is just a way of instructing that you should create a EImpl when a class asks for a EInterface or a FSubclass when a class asks for a FClass. This language also lets you choose when to create new instances: On every request, once across the whole app ("singleton"), or otherwise. Spring uses XML and Guice uses a custom Java class language for this; Dagger uses Java interfaces, classes, and annotations.
You can do dependency injection without a container or framework, but most of the time people think of a framework like Spring, Guice, or Dagger when you mention dependency injection. These frameworks automate away a lot of the new boilerplate you see above, which could otherwise make "manual" dependency injection hard to work with.
What about JSR 330?
Java standardized some interfaces and annotations as "JSR 330" to make it easier to switch between dependency injection frameworks, and to make it easy to write libraries that work in any framework. Like Spring and Guice, Dagger conforms to this standard.
Why is it a big deal that Dagger is compile-time?
Other dependency injection frameworks, including Spring and Guice, do their configuration at runtime: They use Java reflection to inspect classes' constructors, methods, and fields. This can be slow in production on servers and desktops, and is extremely slow on Android due to both VM differences and mobile processor/memory constraints. Consequently, teams at Square and Google wrote Dagger and Dagger 2 to use Java annotation processing to inspect the classes at compile time and automatically write standard Java code for plain Java objects to act like the factories above. Because this is plain Java without reflection, it can be much faster on Android and embedded systems, and can be optimized using existing tools.
Note, as well, that Dagger was written at Square by Bob Lee (who originally wrote Guice at Google); the Dagger 2 project is rewrite of Dagger maintained at Google that changes some of the specifics about how to configure Dagger and how to avoid using reflection. Both Dagger and Dagger 2 are annotation-based compile-time dependency injection frameworks for Java, but they're slightly different from one another.
What is dependency injection actually?
You will find a lot of technical contents about dependency injection but maximum time new learners find stuck to figure out the basic understanding of DI. Here is a real-life example of DI.
Importance of DI
Increase reusabilities of code
Good balance of loosely coupled dependancies
Ease to refactoring
Ease to test and debug
What is dagger?
Dagger is a DI framework that will generate a lot of boilerplate code for you to achieve the goal of dependency injection in Android development.
When to use dagger?
I got a clear vision of DI also with dagger from Android Dev Summit '19 session hopefully which will also clear your vision.

Is a Component optional to use in Dagger 2?

There is one approach mentioned in http://www.vogella.com/tutorials/Dagger/article.html#connecting-consumers-and-providers and other approch without using Component here http://antonioleiva.com/dagger-android-part-2/.
First, please note that Dagger 2 and Dagger are not the same thing. If you read ObjectGraph you are probably reading about Dagger (1).
You can not use Dagger 2 without components. Components are the objects that hold your dependencies and know how to provide and inject them. I think the same holds true for Dagger 1 about their ObjectGraph. If you don't have the means to provide your dependencies, you can't use DI.

Dagger best practice

I'm trying to figure out dagger and having a hard time to grasp the concept of the object graphs.
I'm not new to the dependency injection paradigm, I used angular.js in JavaScript and prism in .Net. So I do understand the idea behind it.
What I can't seem to understand is whether the object graph should be actually a single graph, meaning one in all the app and all the dependencies should be injected from it or should I create one for each module.
I want to create an instance of a class with injectables, so should I use an existing object graph or create a new one?
Where is best practice to create multiple mudules ? Should I create object graph per module as a singleton? Create one object graph for all the app that every class should use? Or should I create a new object graph each time I need a new instance?
Thanks
Think of Object Graphs or Components (if using dagger2) as a way to scope objects. You mentioned you used .Net so I am assuming you are familiar with scoping. Rather than creating a graph for each module I would recommend creating an object graph for each scope. A common pattern is to have an Application scope and then "plus" the activity graph/component onto the Application scope. You can have 1 to many modules per component. Modules are more of a way to split dependencies into different files (even thought they may still be in same component). CodePath has a pretty good intro on Dagger including going into scopes as well as multiple modules per component. Best of Luck! https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2

Singletons in Dagger 1.x

When using Dagger, I found that I'm getting multiple instances of a singleton when I inject it wherever I need it. I've annotated the class and the provides method with #Singleton. Can anyone think of why this is happening?
Edit:
If it helps, I have followed the same structure for my app as the sample application in Dagger's GitHub (https://github.com/square/dagger/tree/master/examples/android-activity-graphs). I'm trying to get the Singleton in the base activity and a couple of third party classes provided using #Provides at the custom Application class. Is it because I'm plus-ing modules at each activity to the original object graph?
(PS : I'm new to Dagger and DI in general, so I'll be grateful if you could provide an explanation so that I may learn. Thanks.)
#Singleton, in Dagger 1.x, acts differently than you might think. The JSR-330 spec definition in the #Singleton javadoc is "one per graph" and that is how Dagger interprets it.
So if you have something that is marked as #Singleton, and it is materialized in your application graph (as opposed to a shorter-lifetime graph), then you get one instance per application.
If you have an item annotated #Singleton that's in the modules you use to configure your activity graph (i.e., that is obtained from the part of a graph specified by a module used in the plus() operation) then you will get one-per-activity-graph.
If you need something to be once-per-application, you need to make sure it gets created as a part of the application graph. You can do this in one of two ways. Either explicitly provide it with an #Provides method from your application module(s), or you can list it as a one of the classes in #Module(injects=...) in an application module.
(If you do not mark it with #Singleton than you will get one per injection site.)
So remember, the graph created by plus() is seen as a separate graph that points to the graph from which it was spawned, and wraps it, can access instances within it, but is not the same graph.
Note - Dagger 2.x improves this, and supports custom scoping annotations, though the mechanism is similar, with one graph (component) per scope annotation, with a parent/child relationship between graphs of wider/narrower lifetimes

Categories

Resources