Dal*_*gia 15 java android dagger dagger-2
我正在开发一个Android库,它基本上是我编写的一些REST服务的客户端.我有几个存储类,网络队列,解析器等,并且像许多这样的类一样,它们依赖于Context或者SharedPreferences构建自的东西Context.这些对象都隐藏在facade类后面,因此我的库的使用者看不到它们或直接与它们交互.
为了我自己的理智,我想使用Dagger 2进行依赖注入,以便在我的库中管理这些类的实例.但是,我不想强迫使用我的库的应用程序自己使用Dagger; 仅仅因为我选择使用Dagger并不意味着我的用户应该这样做.
我见过的所有教程似乎都期望我正在构建一个应用程序,而不仅仅是一个库.这些教程中的许多都告诉我应该让我的Application类继承自己DaggerApplication.但就我而言,我的库中根本没有Application(或任何Activity或Service`类),我不希望我的用户必须使用Dagger的基类.
那么我如何才能使用Dagger而不将其"泄漏"出我的库?我在这里找到了部分答案,但我不确定如何调整作者的"包装"模式来处理我对它的依赖Service.我可以将上下文传递给包装器的Context方法,还是Dagger能够以其他方式获取Context引用?
Mar*_*ini 16
库几乎就像一个应用程序(当谈到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;
}
}
Run Code Online (Sandbox Code Playgroud)
您的"模块"可能如下所示:
@Module
public class YourModule {
private Context context;
public YourModule(Context context) {
this.context = context;
}
@Provides
@Singleton
final Context providesContext() {
return context;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
让您的用户调用方法(或者如果组件为null,则第一次调用它):
DaggerInjector.buildComponent(context);
Run Code Online (Sandbox Code Playgroud)
这将确保初始化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
}
Run Code Online (Sandbox Code Playgroud)
并且在任何"可注入"对象(即,inject在组件中具有方法的对象......)中,您可以执行以下操作:
public class AnObjectThatWantsToInjectStuff {
@Inject
SomeObject someObject;
@Inject
SomeOtherObject someOtherObject;
public AnObjectThatWantsToInjectStuff() {
super();
DaggerInjector.getComponent().inject(this);
// you can now use someObject and someOtherObject
}
}
Run Code Online (Sandbox Code Playgroud)
为了使上述工作,您需要在YourComponent(这是一个接口)代码中这样:
void inject(AnObjectThatWantsToInjectStuff object);
(否则DaggerInjector.getComponent().inject(this)在编译时调用会失败)
请注意,我从未传递过上下文YourInjectableContext,Dagger已经知道如何获取它.
泄漏时要小心.我建议你为所有/大多数情况存储context.getApplicationContext()而不是仅仅是普通Context的(除非你明确需要一个Activity上下文来膨胀布局/主题目的,消费应用程序提供的应用程序上下文就是你所需要的).
| 归档时间: |
|
| 查看次数: |
960 次 |
| 最近记录: |