Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Nik Kober Avatar asked Jan 05 '23 04:01

Nik Kober


1 Answers

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.

like image 118
Konrad Krakowiak Avatar answered Jan 08 '23 23:01

Konrad Krakowiak