Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to scope constructor injection in dagger 2?

Tags:

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();
   }
}
like image 871
Rubin Yoo Avatar asked Sep 07 '16 17:09

Rubin Yoo


People also ask

What is @inject in constructor Dagger?

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.

Can we create custom scope in Dagger 2?

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.

How do you inject a class in Dagger 2?

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.

What are scopes in Dagger 2?

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.


1 Answers

You need to put the scope on the class

@AppScope
public class Blah {
    @Inject StackOverFlow stackOverflow;

    @Inject 
    public Blah()  {
    }
}
like image 123
EpicPandaForce Avatar answered Sep 23 '22 17:09

EpicPandaForce