牙签不会在注入的实例中注入依赖项

Toothpick doesn't inject dependencies in injected instance

我创建了 Activity、ViewModel、Toothpick 和 Authenticator 模块。

@Singleton
public class GetSmsViewModel {

    @Inject Application app;

    @Inject Authenticator authenticator;
...
}


public class GetSmsActivity extends AppCompatActivity {

    private Scope appScope;
    @Inject GetSmsViewModel mGetSmsViewModel;
...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        appScope = Toothpick.openScope(getApplication());
        appScope.installModules(new DIModule(getApplication()), new DataModule());

        super.onCreate(savedInstanceState);

        Toothpick.inject(this, appScope);

   ...
   }
}

public class DIModule extends Module {
    public MagicDeliveryMainModule(Application application) {
        bind(GetSmsViewModel.class).toInstance(new GetSmsViewModel());
        bind(Application.class).toInstance(application);
        bind(Authenticator.class).toInstance(new Authenticator());
    }
}

在 Toothpick 的文档中写道:"If Toothpick creates an instance, it will always inject its dependencies.",但在 Toothpick.inject(this, appScope) 之后;

mGetSmsViewModel.app == null 和 mGetSmsViewModel.authenticator == null 。之后 Toothpick.inject(mGetSmsViewModel, appScope); app 和 authenticator 字段被注入。

应该是这样?

在你的例子中,Toothpick 没有创建实例,你正在创建实例并绑定它。

要让 toothpick 创建实例,您需要绑定到目标实现 class 并提供注入构造函数。