Dagger 2: Provide same instance between multiple Component with same Scope on different library modules

前端 未结 1 687
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 12:01

I have a Core Android Library where I\'m defining a CoreComponent ad using the @Singleton scope to inject instances of classes provided by a CoreModule.

@Sin         


        
相关标签:
1条回答
  • 2020-12-16 12:14

    Remove the injection sites from your CoreComponent - it now has the sole function of exposing the binding for CoreRepository to its dependent components:

    @Singleton
    @Component(modules = {CoreModule.class})
    public interface CoreComponent {
        CoreRepository coreRepository();
    }
    

    Create a reference to this singleton-scoped component inside your application:

    public class MyApplication extends Application {
        private final CoreComponent coreComponent;
    
        @Override
        public void onCreate() {
            super.onCreate();
            coreComponent = DaggerCoreComponent
                                .coreModule(new CoreModule())
                                .build();
        }
    
        public static CoreComponent getCoreComponent(Context context) {
            return ((MyApplication) context.getApplicationContext()).coreComponent;
        }
    }
    

    Create a new narrower scope:

    @Scope
    @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {}
    

    Create a new component that tracks this scope complete with the injection sites you want:

    @PerActivity
    @Component(dependencies = {CoreComponent.class})
    public interface ActivityComponent {
        void inject(FooActivity activity);
    
        void inject(BarActivity activity);
    }
    

    When you access this activity-scoped component in the injection site, you will need to provide the instance of CoreComponent to the builder. Now you can inject into your Activity

    public class FooActivity extends AppCompatActivity {
            @Inject
            public CoreRepository repo;
    
            @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                CoreComponent coreComponent = MyApplication.getCoreComponent(this);
                DaggerActivityComponent.builder()
                    .coreComponent(coreComponent)
                    .build()
                    .inject(this);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题