Dagger 2 how to perform constructor injection

前端 未结 2 1313
说谎
说谎 2020-12-19 02:40

I have a class

public class DialogUtils
{
    private Context context;

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


        
相关标签:
2条回答
  • 2020-12-19 02:53

    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
    
    0 讨论(0)
  • 2020-12-19 03:03

    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
    }
    
    0 讨论(0)
提交回复
热议问题