Skip to content

Proposal: provide your own MembersInjector instance in a module #1046

@scameronde

Description

@scameronde

As far as I have understood dagger, there are two ways for Dagger to know how to create an object:

  1. scanning for annotations at constructors
  2. scanning modules for provider methods

With injection, the situation is not that easy. If you combine creation and injection, then everything is fine:

  1. scanning for annotations at fields or methods
  2. scanning modules for method parameters of provider methods

When I only want to use injection, because the object got already created by some other party, things are different. In this case Dagger only supports this:

  1. scanning for annotations at fields or methods to create a MembersInjector that can be used at component level with an inject method.
  2. not supported: providing an implementation of a MembersInjector in a module

What I would like to do is something like this:

// imported from some library. instances get created but not initialized by the library
final class Type {
  A a;
  B b;

  private Type() {}

  public void initialize(A a, B b) {this.a=a; this.b=b};
} 

My component and modules can provide A and B.

What I am looking for is something like

@Component(modules = MyModule.class)
interface MyComponent {
  Type inject(Type t);
}

and a way to provide my own implementation of the MembersInjector. Like this:

@Module
class MyModule {
  @Injects
  MembersInjector<Type> provideTypeInjector(A a, B b) {
    return instance -> {
      instance.initialize(a, b);
    }
  }
}

Dagger can then generate the necessary code for DaggerMyComponent.

I know I can write something myself. A pattern might be:

interface MyInjector<T> {
  T inject(T);
}

@Module
class MyModule {
  @Provides
  MyInjector<Type> provideTypeInjector(A a, B b) {
    return instance -> {
      instance.initialize(a, b);
    }
  }
}

@Component(modules = MyModule.class)
interface MyComponent {
  MyInjector<Type> getTypeInjector();
}

Initializing the object can then be achieved by doing:

component.getTypeInjector().inject(typeInstance);

but I think

component.inject(typeInstance);

would be much nicer and more idiomatic.

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions