1

I have a question about Dagger constructor injections.

If I were to have a constructor injection for one class - however, the constructor also needs to take in a parameter at run time. How do I have the "Bar" in the below example being injected from a provided module?

For ex:

class Foo {

      public static final class Factory {
           @Inject Factory() {
           }

            public Foo create(final DynamicRuntimeObj random) {
                 return new Foo(random);
           }
       }

       Bar mBar;
       DynamicRuntimeObj mRandom;

       @Inject
       Foo(Bar bar, DynamicRuntimeObj random) {
           mBar = bar;
           mRandom = random;
       }
 }

Normally, I could create the object like this

Foo foo = new Foo.Factory().create(new DynamicRuntimeObj());

with bar being injected automatically by a provider in one module, but the DynamicRuntimeObj needs to be created at runtime.

Thanks!

Dillon
  • 364
  • 5
  • 18
  • The concept is known as "assisted injection", and there are some [other good SO questions/answers about it](https://stackoverflow.com/q/22799407/1426891). In short, you'll need a Factory like you have, but Dagger's sister project AutoFactory can produce one for you. Before I found Christian's answer there, I also wrote [an answer about it here](https://stackoverflow.com/q/42251057/1426891). – Jeff Bowman Nov 21 '17 at 18:54

1 Answers1

-1

You will have to use @Provides for that

@Provides DynamicRuntimeObj provideMyDependency() {
  return ... // get that obj from somewhere
}
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • I'd like not to use provide for that object. – Dillon Nov 21 '17 at 18:52
  • `@Provides` won't help you here; you'll need a Factory or some other alternative so that consumers can supply their parameters. – Jeff Bowman Nov 21 '17 at 18:53
  • @JeffBowman the thing I can think of is to have Factory "injects" the Bar as well and pass the injected param to the Foo constructor. – Dillon Nov 21 '17 at 18:56
  • @Dillon That's what you'll get from your Factory implementation, or from an AutoFactory. There's no way for `@Provides` to accept a parameter from a consumer. – Jeff Bowman Nov 21 '17 at 19:00
  • 1
    Thanks! I guess my actual question was if there is a "cleaner" way of doing it. The answer is to use the Autofactory. – Dillon Nov 21 '17 at 19:03