Use Dagger modules without the “injects” directive

前端 未结 1 414
孤街浪徒
孤街浪徒 2021-02-01 21:33

I am trying to make Dagger work without the \"injects\" directive inside the @Module annotation. I am basing my test project on the Android Simple Dagger example

This i

1条回答
  •  遇见更好的自我
    2021-02-01 22:21

    You want

    @Module(library=true)
    

    Here's what the docs say about library:

    False if all the included bindings in this module are necessary to satisfy all of its injectable types. If a module is not a library module, it is eligible for additional static checking: tools can detect if included bindings are not necessary. If you provide bindings that are not used by this module's graph, then you must declare library = true.

    (emphasis mine)


    Declaring a module as a library does not alleviate the needs of Dagger to know about injection points. You still must declare a module in the object graph with the listed injects.

    An extreme simplified version of your example would look like this:

    repo/
     +- library/
     |   +- Foo.java
     |   `- FooModule.java
     |
     `- app/
         +- BarActivity.java
         `- BarModule.java
    

    FooModule.java:

    @Module(library = true)
    public final class FooModule {
      @Provides @Singleton provideFoo() {
        return Foo();
      }
    }
    

    BarModule.java:

    @Module(
      injects = BarActivity.class,
      includes = FooModule.class
    )
    public final class BarModule {
    }
    

    In BarActivity.java (or similar):

    ObjectGraph og = ObjectGraph.create(new BarModule());
    og.inject(this);
    

    0 讨论(0)
提交回复
热议问题