Dagger 2 how to perform constructor injection

删除回忆录丶 提交于 2019-12-04 02:59:50

问题


I have a class

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.


回答1:


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;
    }
}

then

@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);
}

And then

@Inject
DialogUtils dialogUtils;

...


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

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



回答2:


On the one hand you are registering DialogUtils for Constructor Injection, so any component could provide it.

On the other hand an activity and other parts of the Android Framework still need to be field injected. Dagger can't call their constructor, and @Inject DialogUtils dialogUtils; will not just magically appear.

Here you have to use a component, and register a method that takes your components type as an argument. Dagger will then create the method to inject your activities fields.

@Component MyComponent {
  inject(LoginActivity activity);
}

To inject the fields you still have to create your component, and call the inject(loginActivity) method.

void onCreate(...) {
  MyComponent component = // create the component

  // dagger does some heavy lifting here
  component.inject(this);

  dialogUtils.doSomething(); // not null, we just injected our fields
}


来源:https://stackoverflow.com/questions/45192878/dagger-2-how-to-perform-constructor-injection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!