Leem
Leem

Reputation: 18308

Make a class injectable and a singleton with Dagger annotation only

I know there are tutorials of how to define singleton with Module. But my question is not really on that. I mean Dagger also provides a way to make a class injectable to Android component by annotate that class's empty constructor without declare anything in Module, right? e.g.

public class MyApi {

    @Inject
    public MyApi(){
    }
}

So, I can inject MyApi to an Fragment by :

class MyFragment extends Fragment {
   @Inject
   protected MyApi myApi;
   ...
}

In this way, MyApi doesn't need to be manually declared in Module. Dagger understands it.

My question is if I want MyApi to be a singleton, could I simply add one more annotation like:

public class MyApi {
    @Inject
    @Singleton
    public MyApi(){
    }
}

Would dagger understand it is supposed to be a singleton? Or Do I have to declare in Module like:

@Module
public class MyModule {

    @Provides
    @Singleton
    MyApi providesMyApi() {
        return new MyApi();
    }
}

?

Upvotes: 1

Views: 372

Answers (2)

Xi Wei
Xi Wei

Reputation: 1679

First, add @Singleton on top of the class.

@Singleton
public class MyApi {
    @Inject
    public MyApi() {}
 }

Second, you will need to add @Singleton on top of your component interface.

@Singleton
@Component
interface AppComponent {

Here is a completed guide in kotlin if you are interested: https://medium.com/@xiwei/simplest-dagger-example-920bbd10258

Upvotes: 1

Saurabh
Saurabh

Reputation: 1235

for desired behaviour, you need to apply annotation on the class, not constructor. take a look:

 @Singleton
 public class MyApi {

     @Inject
     public MyApi(){
     }
 }

Upvotes: 0

Related Questions