I have a code something like this and I want to make it scoped. But I found that this is not working and it seems only possible through in a module. I wasn't able to find a proper question for this and is it possible to scope a constructor injection?
Does not work
@AppScope
@Inject
public StackOverflow() {
}
Scope works!!
@Module
public InternetModule {
@AppScope
@Provides
public StackOverflow provideStackOverflow() {
return new StackOverflow();
}
}
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.
create custom scopes with Dagger is pretty easy, you just have to follow these steps. Step 1) declare your annotation. Step 2) annotate the dependencies with this annotation in the module.
In order to use dependency injection with the help of dagger 2 libraries, we need to add it's dependency. Go to Gradle Scripts > build. gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.
Scope refers to the lifetime of an object. Consider an example of a simple class. largeScope — Its scope is tied to the lifetime of the class. It can be accessed anywhere in the class.
You need to put the scope on the class
@AppScope
public class Blah {
@Inject StackOverFlow stackOverflow;
@Inject
public Blah() {
}
}
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