I am trying to get Dagger up an working on my project.
However I get the following exception on one of my classes during compilation:
error: No injectable members on Foo. Do you want to add an injectable constructor?
However, the class have no dependencies and as such uses the default no-arg constructor:
public class Foo
{
...
}
Do I really have to add an injectable no-arg constructor like below?
public class Foo
{
@Inject
public Foo()
{
}
....
}
inject. Inject annotation to identify which constructors and fields it is interested in. Use @Inject to annotate the constructor that Dagger should use to create instances of a class. When a new instance is requested, Dagger will obtain the required parameters values and invoke this constructor.
What is singleton? Singleton Pattern in android. A single instance of a class providing a global point of access to itself during the entire application's lifetime. @Singleton annotation in Dagger. A single instance of a class which is unique to a specific component, its access is limited to the scope of the component.
Dagger frees you from writing tedious and error-prone boilerplate code by: Generating the AppContainer code (application graph) that you manually implemented in the manual DI section. Creating factories for the classes available in the application graph. This is how dependencies are satisfied internally.
Now, a module may be a class, and that we annotate it with @Module for Dagger to know it as Module. A component is an interface, which is annotated with @Component and takes modules in it. (But now, this annotation isn't required in Dagger-Hilt).
From the docs:
Classes that lack @Inject annotations cannot be constructed by Dagger.
Dagger actively requires you to add @Inject to your injectable class, either by adding a no-args constructor, or adding an injectable field. The third option is to return the class from an @Provides method like so:
@Module(...)
class MyModule {
@Provides Foo provideFoo() {
return new Foo(); // Foo is not injectable.
}
}
This does seem like extra boilerplate, but from experience with Guice and other frameworks, JIT binding of random classes turns out to be rife with error. We have seen java.lang.String injected into things, and because someone forgot to bind it, you ended up with "" injected instead of the desired string. Dagger, therefore, requires an @Inject constructor, or field.(Guice optionally has this in 4.x, though for backwards compatibility, it is off by default)
This is one rare instance where Dagger has chosen more correctness guarantees at the cost of some small amount of verbosity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With