库几乎类似于应用程序(当涉及到 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;
}
}
使用它:
让你的用户调用一个方法(或者如果组件为空,你自己第一次调用它):
DaggerInjector.buildComponent(context);
这将确保 Dagger 组件已初始化并生成代码。了解调用buildComponent 是一项昂贵的任务(Dagger 必须做很多事情!)所以只做一次(除非您需要使用仅在运行时已知的不同值重新初始化库)。
有些库只是在每次调用中询问上下文,所以这不是不可能的;然后,您可以在第一次调用时初始化 dagger(通过检查 getComponent() 在注入器中是否为空)。
在您的DaggerInjector.getComponent() 不再为空之后,您现在可以添加@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 上下文来扩展布局/主题,否则您只需要使用应用程序提供的应用程序上下文)。