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

时间:2019-01-23 17:56:44

标签: java android toothpick-di

我为牙签和身份验证器创建了Activity,ViewModel,模块。

@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); 应用程序和身份验证器字段被注入。

应该这样吗?

1 个答案:

答案 0 :(得分:0)

在您的示例中,Toothpick没有创建实例,而是在创建实例并将其绑定。

要使用牙签创建实例,您需要绑定到目标实现类并提供注入构造器。