0

我为 Toothpick 和 Authenticator 创建了 Activity、ViewModel、Modules。

@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 的文档中写道:“如果 Toothpick 创建一个实例,它将始终注入其依赖项。” , 但在 Toothpick.inject(this, appScope); 之后

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

应该是这样吗?

4

1 回答 1

0

在您的示例中,牙签没有创建实例,您正在创建实例并绑定它。

要让牙签创建实例,需要绑定目标实现类并提供注入构造函数。

于 2019-01-26T06:14:05.263 回答