从您的位置删除注射位点
CoreComponent-它现在唯一的作用是将
CoreRepository与其相关的组件的绑定公开:
@Singleton@Component(modules = {CoreModule.class})public interface CoreComponent { CoreRepository coreRepository();}
在应用程序内部创建对此单例作用域组件的引用:
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; }}
创建一个新的缩小范围:
@Scope@Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {}
创建一个新组件,以跟踪此范围以及所需的注射部位:
@PerActivity@Component(dependencies = {CoreComponent.class})public interface ActivityComponent { void inject(FooActivity activity); void inject(BarActivity activity);}
当您在注入站点中访问此活动范围的组件时,需要将其实例提供
CoreComponent给构建器。现在您可以注入您的
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条)