Using Dagger for dependency injection on constructors

前端 未结 5 734
故里飘歌
故里飘歌 2021-01-31 17:17

So, I\'m currently redesigning an Android app of mine to use Dagger. My app is large and complicated, and I recently came across the following scenario:

Object A requir

5条回答
  •  野性不改
    2021-01-31 18:01

    What you are talking about is known as assisted injection and is not currently supported by Dagger in any automatic fashion.

    You can work around this with the factory pattern:

    class AFactory {
      @Inject DebugLogger debuggLogger;
    
      public A create(int amount, int frequency) {
        return new A(debuggLogger, amount);
      }
    }
    

    Now you can inject this factory and use it to create instances of A:

    class B {
      @Inject AFactory aFactory;
    
      //...
    }
    

    and when you need to create an A with your 'amount' and 'frequency' you use the factory.

    A a = aFactory.create(amount, frequency);
    

    This allows for A to have final instances of the logger, amount, and frequency fields while still using injection to provide the logger instance.

    Guice has an assisted injection plugin which essentially automates the creation of these factories for you. There have been discussion on the Dagger mailing list about the appropriate way for them to be added but nothing has been decided upon as of this writing.

提交回复
热议问题