Dagger 2 - injecting non Android classes

♀尐吖头ヾ 提交于 2019-11-30 23:20:02

Please don't just use component.inject(myObject) for everything. Always prefer constructor injection or provide it from a module where you can do additional setup steps. .inject(myObject) is intended for Framework components where you don't have access to the constructor.

My first thought was to create a UtilityComponent and a ManagerCompoent of sorts, however I have no idea how I would get them to work with anything in AppModuel or through my AppComponent.

You don't need a separate component for that. See below.

However, since I use these classes outside of Activities, Fragments and ViewModels I cannot just inject.

That has nothing to do with injection. You're talking about scopes, and it sound like your utilities are a @Singleton. Your AppComponent is a @Singleton scoped component, hence it can be used to provide your utils, too.

However, I have cases where I would need a utility class, that depends on Application, for context

If they are part of the @Singleton component, which has access to your Application, they can also be provided anywhere else. No need for more components or anything. Just declare your dependencies and don't overthink it.


Just declare your util, annotate it with @Singleton and mark the constructor with @Inject for constructor injection. @Singleton ensures that it will be provided by your AppComponent and can access the Application on which it depends.

@Singleton public class MyUtil {

  private Application application;

  @Inject public MyUtil(Application application) {
    this.application = application;
  }

}

And then you can just inject it in your Activities, Fragments, or even into other Utilities....

@Singleton public class MyUtilWrapper {

  private MyUtil myUtil;

  @Inject public MyUtilWrapper(MyUtil myUtil) {
    this.myUtil = myUtil;
  }

}

And you can inject either or both into your activity or fragment...

@Inject MyUtil myUtil;
@Inject MyUtilWrapper myUtilWrapper;

void onCreate(..) {
  AndroidInjection.inject(this);
}

You do not need any modules, provides methods, or components to provide simple classes. Just make sure to add the right scope!

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