简体   繁体   English

Dagger2注入子对象

[英]Dagger2 injection into child object

Not sure the title is clear but what I actually have is : 不确定标题是否清晰,但是我实际拥有的是:

module : 模块:

@Module
public class TestUserModule {

    User user;

    public TestUserModule(User user) {
        this.user = user;
    }

    @Provides
    @Singleton
    public User providesUser() {
        return user;
    }
}

Component : 零件 :

@Singleton
@Component(modules = {TestUserModule.class})
public interface UserComponent {

    void inject(MyActivity activity);
    void inject(MyActivity2 activity);
}

in my App I create the component like this : 在我的应用程序中,我创建这样的组件:

userComponent = DaggerUserComponent.builder().testUserModule(new TestUserModule(user)).build();

So, in my activity everything is ok, I can use @Inject User user; 因此,在我的活动中一切正常,我可以使用@Inject User user; it works fine. 它工作正常。

Now in my Activity, if I create an Object Foo, which look like this : 现在在我的Activity中,如果我创建一个Object Foo,它看起来像这样:

public class Foo {

@Inject
User user;

MyActivity activity;

public Foo(MyActivity activity){
this.activity = activity;
}
} 

By instantiating Foo in my activity with new Foo() , I know my user will not be injected. 通过使用new Foo()实例化活动中的new Foo() ,我知道不会注入用户。

So my question is, what I have to update in my code to be able to inject Foo object in my activity (I think this is the way to do if I want to inject User in Foo but tell me if I'm wrong) ? 所以我的问题是,我必须在代码中更新什么才能在活动中注入Foo对象(我想如果要在Foo中注入User但告诉我是否错误)就是这样做的方法。

Also, where is a good place to build my component ? 另外,在哪里构建我的组件的好地方? Everything in the App ?? 应用中的所有内容?

Thank's 谢谢

You have 4 choices: 您有4个选择:

1. Use: 1.使用:

@Inject
Foo mFoo;

Use this approach if lifecycle of foo is exactly the same as lifecycle of your activity. 如果foo的生命周期与活动的生命周期完全相同,请使用此方法。

2. Use Lazy : 2.使用Lazy

@Inject
Lazy<Foo> mLazyFoo;

and then when you need the instance of Foo : 然后在需要Foo实例时:

Foo myFoo = mLazyFoo.get();

Use this approach if you will need just one Foo for the entire lifecycle of the activity. 如果您在活动的整个生命周期中只需要一个Foo,请使用此方法。

3. Use Provider 3.使用Provider

@Inject
Provider<Foo> mFooProvider;

and when you need instance an instance of Foo 当您需要实例时,可以使用Foo的实例

Foo myFooFirstInstance = mFooProvider.get();

Use this approach when you will need more than one instance of Foo in your activity. 当您的活动中需要多个Foo实例时,请使用此方法。

4. Inject your foo manually (not recommended): 4.手动注入foo(不推荐):

In your UserComponent declare void inject(Foo foo) and then in your method: 在您的UserComponent声明void inject(Foo foo) ,然后在您的方法中声明:

Foo myFoo = new Foo(...);
userComponent.inject(myFoo);

Also, where is a good place to build my component ? 另外,在哪里构建我的组件的好地方? Everything in the App ?? 应用中的所有内容?

For android app: yes, usually the component is built there. 对于android应用程序:是的,通常组件是在此处构建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM