Nik Kober
Nik Kober

Reputation: 918

Dagger 2 inject singleton without module

I am using Dagger 2 injection to provide some dependency to client:

public class Dependency {

    @Inject
    Dependency() {
    }

    void check() {
        System.out.print("Instantiated");
    }
}

public class Client {

    @Inject Dependency dependency;

    Client() {
        ClientComponent component = DaggerClientComponent.create();
        component.inject(this);
    }

    void checkDependency() {
        dependency.check();
    }
}

@Component
public interface ClientComponent {
    void inject(Client client);
}

public class Test {
    public static void main(String... args) {
        Client client = new Client();
        client.checkDependency();
    }
}

It works fine, but now I want to make my dependency singleton. How can I achieve it? Should I create module for this dependency and annotate provide method with singleton annotation or I have another options to avoid module creation?

Upvotes: 5

Views: 7641

Answers (1)

Konrad Krakowiak
Konrad Krakowiak

Reputation: 12365

Add @Singleton on the top of your class and add @Singleton annotation to your component.

@Singleton
public class Dependency {

    @Inject
    Dependency() {
    }

    void check() {
        System.out.print("Instantiated");
    }
}

@Singleton
@Component
public interface ClientComponent {
    void inject(Client client);
}

You should also move creation of your component to better place - onCreate method from app object is right place.

Upvotes: 11

Related Questions