我正在开发一个Android库,它基本上是我编写的一些REST服务的客户端。我有几个存储类,网络队列,解析器等,并且像许多这样的类一样,它们依赖于Context
或SharedPreferences
构造的Context
之类的东西。这些对象都隐藏在facade类后面,因此我的库的使用者看不到它们或直接与它们交互。
为了我自己的理智,我想使用Dagger 2进行依赖注入,以便在我的库中管理这些类的实例。但是,我不想强迫使用我的库的应用程序自己使用Dagger;仅仅因为我选择使用Dagger并不意味着我的用户应该这样做。
我见过的所有教程似乎都期望我正在构建一个应用程序,而不仅仅是一个库。其中许多教程告诉我,我应该让我的Application
类继承自DaggerApplication
。在我的情况下,我的库中根本没有Application
(或任何Activity
或Service
类),我不希望我的用户必须使用Dagger的基类。
那么我如何才能使用Dagger而不将其“泄漏”出我的库?我找到了一个部分答案here,但我不确定如何调整作者的“包装”模式来处理我对Context
的依赖。我可以将上下文传递给包装器的getComponent()
方法,还是Dagger能够以其他方式获取Context引用?
库几乎就像一个应用程序(当谈到Dagger时)。是的,你没有application
对象,但你真的不需要它。
作为图书馆的消费者,我希望它的使用简单,所以我不想知道匕首是什么(或者如果你在内部使用它)。
让您的用户在第一次调用您的库时通过Context
(例如)。有一个DaggerInjector
(我认为你的样本称之为包装器),它有一个静态引用你的Component
接口。
示例(因此,只是一个通用示例):
public class DaggerInjector {
private static YourComponent component;
private DaggerInjector() {
super();
}
public static YourComponent getComponent() {
return component;
}
public static YourComponent buildComponent(Context context) {
component = DaggerYourComponent
.builder()
.yourModule(new YourModule(context))
.build();
return component;
}
}
您的“模块”可能如下所示:
@Module
public class YourModule {
private Context context;
public YourModule(Context context) {
this.context = context;
}
@Provides
@Singleton
final Context providesContext() {
return context;
}
}
要使用它:
让您的用户调用方法(或者如果组件为null,则第一次调用它):
DaggerInjector.buildComponent(context);
这将确保初始化Dagger组件并生成代码。理解调用buildComponent
是一项昂贵的任务(Dagger必须做很多事情!)所以只做一次(除非您需要使用运行时已知的不同值重新初始化库)。
有些图书馆只是在每个电话中都要求一个上下文,所以这不是不可能的;然后,你可以在第一次调用时初始化dagger(通过检查注入器中的getComponent()是否为null)。
在您的DaggerInjector.getComponent()
不再为null之后,您现在可以添加@Inject
和相应的“可注射”内容......
例如:在YourModule
你可以:
@Provides
SomeObject providesSomeObject() {
return new SomeObject();
}
// THIS “Context” here is automatically injected by Dagger thanks to the above.
@Provides
@Singleton
SomeOtherObject providesSomeOtherObject(Context context) {
return new SomeOtherObject(context); //assume this one needs it
}
并且在任何“可注入”对象(即,在组件中具有inject
方法的对象......)中,您可以执行以下操作:
public class AnObjectThatWantsToInjectStuff {
@Inject
SomeObject someObject;
@Inject
SomeOtherObject someOtherObject;
public AnObjectThatWantsToInjectStuff() {
super();
DaggerInjector.getComponent().inject(this);
// you can now use someObject and someOtherObject
}
}
为了使上述工作,您需要在YourComponent
(这是一个接口)代码,如下所示:
void inject(AnObjectThatWantsToInjectStuff object);
(否则在编译时调用DaggerInjector.getComponent().inject(this)
会失败)
请注意,我从未向YourInjectableContext
传递过上下文,Dagger已经知道如何获取它。
泄漏时要小心。我建议你为所有/大多数情况存储context.getApplicationContext()
而不是普通的Context
(除非你明确需要一个Activity上下文来膨胀布局/主题目的,消费应用程序提供的应用程序上下文就是你所需要的)。