Dagger 2如何执行构造函数注入 [英] Dagger 2 how to perform constructor injection

查看:67
本文介绍了Dagger 2如何执行构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课

public class DialogUtils
{
    private Context context;

    @Inject
    public DialogUtils(Context context)
    {
        this.context = context;
    }
}

在我的活动课程中,我做了,但是我

In my activity class i have did but i'm getting null pointer exception on dialogUtils instance.

public class LoginActivity extends Activity{
@Inject DialogUtils dialogUtils;
}

我知道如何通过模块和组件注入依赖关系,但不确定如何使用建筑注射。非常感谢您的帮助。

I know how to inject dependency via module and component but not sure how to with construction injection. Any help is much appreciated.

推荐答案

如果您不保留活动级别的组件,并且不会从使用组件依赖项或子组件的超级范围(应用程序级组件),则如下所示:

If you don't retain the activity-level component and you aren't inheriting from a superscope (application-level component) using component dependency or subcomponent, then it's the following

// unscoped
public class DialogUtils {
    private final Context context;

    @Inject
    public DialogUtils(Context context) {
        this.context = context;
    }
}

然后

@Module
public class ActivityModule {    
    private final Context context;

    public ActivityModule (Context context) {
        this.context = context;
    }

    @Provides //scope is not necessary for parameters stored within the module
    public Context context() {
        return context;
    }
}

@Component(modules={ActivityModule.class})
@Singleton
public interface ActivityComponent {
    Context context();

    DialogUtils dialogUtils();

    void inject(MainActivity mainActivity);
}

然后

@Inject
DialogUtils dialogUtils;

...


     ActivityComponent activityComponent = DaggerMainActivityComponent.builder()
        .activityModule(new ActivityModule(MainActivity.this))
        .build();

    activityComponent.inject(this); // activityComponent.dialogUtils() also works

这篇关于Dagger 2如何执行构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆