My dagger configuration for an android project that i'm working on:
Note: I've provided all the needed #Component, #Module, #Provides annotations wherever needed.
MainActivity {
#Inject A a;
#Inject B b;
onCreate(){
ComponentX.inject(this);
ComponentY.inject(this);
}
}
ComponentX-> ModuleA ->providerA
ComponentY -> ModuleB -> providerB
As you can see, these are two completely independent components not related to each other in anyway except for at the point of injection.
During compilation I get the following error:
In file A.java
error: B cannot be provided without an #Provides- or #Produces-annotated method.
MainActivity.b
[injected field of type: B b]
Am I mistaken in thinking that multiple components can be used while using dagger 2 or is the application supposed to use one big component which takes care of all the injections?
Can anyone help me understand where i'm going wrong?
You do not have to have a single component, there are various ways to modularize them, but each object that you create, or inject values into, must have all its values provided by a single component.
One way you could restructure your code is to have ComponentY depend on ComponentX, or vice versa, e.g.
#Component(dependencies = ComponentX.class)
interface ComponentY {
void inject(MainActivity activity);
}
Or you could create a third Component, say ComponentZ, if ComponentX and ComponentY are completely orthogonal to one another.
#Component(dependencies = {ComponentX.class, ComponentY.class})
interface ComponentZ {
void inject(MainActivity activity);
}
Or you could just reuse the modules, e.g.
#Component(modules = {ModuleA.class, ModuleB.class})
interface ComponentZ {
void inject(MainActivity activity);
}
How exactly you decide to split it largely depends on the structure of your code. If the components X and Y are visible but the modules are not then use component dependencies, as they (and module depedencies) are really implementation details of the component. Otherwise, if the modules are visible then simple reuse them.
I wouldn't use scopes for this as they are really for managing objects with different lifespans, e.g. objects associated with a specific user whose lifespan is the time from when a user logs in to when they log out, or the lifespan of a specific request. If they do have different lifespan then you are looking at using scopes and subcomponents.
is the application supposed to use one big component
Kind of, you should think of it in scopes. For a given scope, there is one component. Scopes are for example ApplicationScope, FragmentScope (retained), ActivityScope, ViewScope. For each scope, there is a given component; scopes are not shared between components.
(This essentially means that if you want to have global singletons in the #ApplicationScope, there is one application scoped component for it. If you want activity-specific classes, then you create a component for it for that specific activity, which will depend on the application scoped component).
Refer to #MyDogTom for the #Subcomponent annotation, but you can also use component dependencies for the creation of subscoped components as well.
#YScope
#Component(dependencies = ComponentX.class, modules=ModuleB.class)
public interface ComponentY extends ComponentX {
B b();
void inject(MainActivity mainActivity);
}
#XScope
#Component(modules=ModuleA.class)
public interface ComponentX{
A a();
}
ComponentY componentY = DaggerComponentY.builder().componentX(componentX).build();
is the application supposed to use one big component which takes care
of all the injections?
You can use Subcomponent. In your case components declaration will look like this:
#Subcomponent(modules=ModuleB.class)
public interface ComponentY{
void inject(MainActivity mainActivity);
}
#Component(modules=ModuleA.class)
public interface ComponentX{
ComponentY plus(ModuleB module);
}
ComponentY creation: creationCompunentY = ComponentX.plus(new ModuleB());
Now in MainActivity you call only ComponentY.inject(this);
MainActivity {
#Inject A a;
#Inject B b;
onCreate(){
ComponentY.inject(this);
}
}
More information about sub components can be found in migration from Dagger1 guide (look at Subgraphs part), Subcomponent JavaDoc and Component JavaDoc (look at Subcomponents part).
Related
My team owns a library that provides components that must be referencable by code that consumes the library. Some of our consumers use Spring to instantiate their apps; others use Guice. We'd like some feedback on best-practices on how to provide these components. Two options that present themselves are:
Have our library provide a Spring Configuration that consumers can #Import, and a Guice Module that they can install.
Have our library provide a ComponentProvider singleton, which provides methods to fetch the relevant components the library provides.
Quick sketches of what these would look like:
Present in both approaches
// In their code
#AllArgsConstructor(onConstructor = #__(#Inject))
public class ConsumingClass {
private final FooDependency foo;
...
}
First approach
// In our code
#Configuration
public class LibraryConfiguration {
#Bean public FooDependency foo() {...}
...
}
---
public class LibraryModule extends AbstractModule {
#Provides FooDependency foo() {...}
...
}
========================
========================
// In their code
#Configuration
#Import(LibraryConfiguration.java)
public class ConsumerConfiguration {
// Whatever initiation logic they want - but, crucially, does
// *not* need to define a FooDependency
...
}
---
// *OR*
public class ConsumerModule extends AbstractModule {
#Override
public void configure() {
// Or, simply specify LibraryModule when creating the injector
install(new LibraryModule());
...
// As above, no requirement to define a FooDependency
}
}
Second approach
// In our code
public class LibraryProvider {
public static final INSTANCE = buildInstance();
private static LibraryProvider buildInstance() {...}
private static LibraryProvider getInstance() {return INSTANCE;}
}
========================
========================
// In their code
#Configuration
public class ConsumerConfiguration {
#Bean public FooDependency foo() {
return LibraryProvider.getInstance().getFoo();
}
...
}
// or equivalent for Guice
Is there an accepted Best Practice for this situation? If not, what are some pros and cons of each, or of another option I haven't yet thought of? The first approach has the advantage that consumers don't need to write any code to initialize dependencies, and that DI frameworks can override dependencies (e.g. with mocked dependencies for testing); whereas the second approach has the advantage of being DI-framework agnostic (if a new consumer wanted to use Dagger to instantiate their app, for instance, we wouldn't need to change the library at all)
I think the first option is better. If your library has inter-dependencies between beans then the code of #Configuration in case of spring in the second approach) will be:
Fragile (what if application doesn't know that a certain bean should be created)
Duplicated - this code will appear in each and every consumer's module
When the new version of your library gets released and a consumer wants to upgrade- there might be changes in consumer's configuration ( the lib might expose a new bean, deprecate or even remove some old stuff, etc.)
One small suggestion:
You can use Spring factories and then you don't even need to make an #Import in case of spring boot. just add a maven dependency and it will load the configuration automatically.
Now, make sure that you work correctly with dependencies in case of that approach.
Since you code will include both spring and Juice dependent code, you'll add dependencies on both for your maven/gradle module of the library. This means, that consumer that uses, say, guice, will get all the spring stuff because of your library. There are many ways to overcome this issue depending on the build system of your choice, just want wanted to bring it up
I started working on a new Android project from scratch. After understanding the project scope and requested features, I've came up with a modular architecture (basically wrapping every feature into a feature or android module) that looks as following
Everything looks perfect until I wanted to introduce dagger to glue all the modules. The problem is that I want every module to has its own dagger component/subcomponent and it's modules in order to provide dependencies and expose them the graph to be using by other component or the parent one.
Google official dagger documentation states that subcomponents has direct access to parent component dependencies' and not vice versa. However, in my case the base component require dependencies from the data module and this latter itself require dependencies from the network module.
is there any solution for this problem knowing that i want every android module to have its own sub-component preferably? If not, is there any solution anyway?
Thank you.
Edit:
Here is how my project structure looks like
And this is how I setup my dagger graph
My AppComponent(Dagger root)
#Singleton
#Component(modules = {
AppModule.class,
ActivityBuilder.class,
AndroidSupportInjectionModule.class
})
public interface AppComponent {
void inject(CatApp application);
#Component.Builder
interface Builder {
#BindsInstance
Builder application(Application application);
AppComponent build();
}
}
My App Module
#Module(subcomponents = DataComponent.class)
public class AppModule {
#Provides
#Singleton
Context provideContext(Application application) {
return application.getApplicationContext();
}
}
My DataComponent (located at the data android module)
#Subcomponent(modules = DataModule.class)
public interface DataComponent {
#Subcomponent.Builder
interface Builder {
DataComponent build();
}
}
Data module (located at data android module) that should provide the implementation of SystemManager
#Module(subcomponents = NetworkComponent.class)
public class DataModule {
#Provides
#Singleton
ISystemManager provideSystemManager(SystemManager systemManager) {
return systemManager;
}
}
Network Component (located at Network Android Module)
#Subcomponent(modules = NetworkModule.class)
public interface NetworkComponent {
#Subcomponent.Builder
interface Builder {
NetworkComponent build();
}
}
Network Module (located at Network Android Module) and should provide implementation of INetWorkManager
#Module
public class NetworkModule {
#Provides
#Singleton
INetworkManager provideNetworkManager(NetworkManager networkManager) {
return networkManager;
}
}
I am using #Inject annotation at all constructors so my configurations is all setup but the issue is that dagger doesn't compiles these subcomponent for some reason and I get this error when compiled:
Error:(27, 8) error: [dagger.android.AndroidInjector.inject(T)] com.github.andromedcodes.network.INetworkManager cannot be provided without an #Provides-annotated method.
com.github.andromedcodes.network.INetworkManager is injected at
com.github.andromedcodes.data.SystemManager.<init>(networkManager)
com.github.andromedcodes.data.SystemManager is injected at
com.github.andromedcodes.data.di.DataModule.provideSystemManager(systemManager)
com.github.andromedcodes.domain.managers.ISystemManager is injected at
com.github.andromedcodes.domain.interactors.CheckSystemAvailability.<init>(systemManager)
com.github.andromedcodes.domain.interactors.CheckSystemAvailability is injected at
com.github.andromedcodes.chasseautrsor.views.Splash.SplashPresenter.<init>(checkSystemAvailability)
com.github.andromedcodes.chasseautrsor.views.Splash.SplashPresenter is injected at
com.github.andromedcodes.chasseautrsor.di.SplashModule.bindSplashPresenter(presenter)
com.github.andromedcodes.chasseautrsor.views.Contract.Presenter is injected at
com.github.andromedcodes.mvp.BaseActivity.mPresenter
com.github.andromedcodes.chasseautrsor.views.SplashScreenActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
How can I fix this issue knowing that I want to provide ISystemManager implementation at Data android Module and INetworkManager at Network Android Module?
Thank you.
Subcomponents automatically have access to objects bound in the parent components' graph, which makes sense, because subcomponents have exactly one parent component—there's no ambiguity. Parent components do not have automatic access to subcomponents' graph because you can create as many subcomponent instances as you'd like; it's not clear which instance you're trying to access. In general, unless you need different variations on an object graph (which you'd do with private modules or child injectors in Guice) or unless you wanted to hide implementation details (e.g. internal network objects), you may be better off installing your modules all in the same Component and skipping the subcomponent strategy.
However, if you do want to separate your graph or create multiple subcomponent instances, you could also create a subcomponent instance in a scoped #Provides method. That way NetworkComponent has a separate graph with private bindings, but can also use dependencies you expose in AppComponent, and you can also ensure that there is exactly one copy of NetworkComponent and its relevant bindings in your graph. You'll also need to put a getter (provision method or factory method) on the Subcomponent, so you can access some of its bindings from outside, in exactly the same way that you need a getter or injector method on a #Component for it to be useful.
#Subcomponent(modules = NetworkModule.class)
public interface NetworkComponent {
/** Allow anyone with a NetworkComponent instance to get the INetworkManager. */
INetworkManager getINetworkManager();
#Subcomponent.Builder
interface Builder {
NetworkComponent build();
}
}
/**
* Creates a singleton NetworkComponent. Install this in AppComponent's module,
* or in your data module if that encapsulates network calls.
*/
#Singleton #Provides NetworkComponent networkComponent(
NetworkComponent.Builder builder) {
return builder.build();
}
/** Make the INetworkManager accessible, but not the NetworkManager impl. */
#Provides static provideNetworkManager(NetworkComponent networkComponent) {
return networkComponent.getINetworkManager(); // add this to NetworkComponent
}
For further reference, see the "Subcomponents for Encapsulation" section on in the Dagger 2 docs on Subcomponents:
Another reason to use subcomponents is to encapsulate different parts of your application from each other. For example, if two services in your server (or two screens in your application) share some bindings, say those used for authentication and authorization, but each have other bindings that really have nothing to do with each other, it might make sense to create separate subcomponents for each service or screen, and to put the shared bindings into the parent component.
In the following example, the Database is provided within the #Singleton component, but all of its implementation details are encapsulated within the DatabaseComponent. Rest assured that no UI will have access to the DatabaseConnectionPool to schedule their own queries without going through the Database since that binding only exists in the subcomponent.
My understanding of dependency injection is it quickly allows someone to switch out implementations or use test implementations. I'm trying to understand how you're expected to do it in dagger. For me it seems like you should be able to switch out Module implementations, but that doesn't seem to be supported by dagger. What is the idiomatic way to do it.
For example:
#component{modules = UserStoreModule.class}
class ServerComponent {
Server server();
}
class UserStoreModule {
#Provides
UserStore providesUserStore() {
return // Different user stores depending on the application
}
}
Assuming user store is an interface, what if I want to be able to use a mysql UserStore or a redis UserStore depending on the situation. Would I need to have two different server components? Intuitively I feel like I should be able to switch out which user store I use in The DaggerServerComponent.builder() since that'd be a lot less code than multiple components.
Conceptually, it is true that dependency injection "allows someone to switch out implementations or use test implementations": You've written your classes to accept any implementation of UserStore, and can supply an arbitrary one in a constructor call for tests. This is the case whether or not you use Dagger, and is a big advantage in design.
However, Dagger's most prominent feature--its compile-time code generation--makes it somewhat more limited here than alternatives such as Spring or Guice. Because Dagger generates the classes it needs at compile time, it needs to know exactly which implementations it might encounter, so that it can prepare those implementations' dependencies. Consequently, you couldn't take in an arbitrary Class<? extends UserStore> at runtime and expect Dagger to fill in the rest.
This leaves you with a few options:
Separate Modules, separate Components
Create two separate Module classes, one for each implementation, and use them to let Dagger generate two separate components. This will generate the most efficient code, particularly when using #Binds, because Dagger will not need to generate any code for the implementation you're not binding. Of course, though this allows you to reuse your classes and some of your modules, it doesn't allow the decision between implementations to be made at runtime (short of choosing between entire Dagger component implementations).
This option entails a very small amount of handwritten code, but does generate a lot of extra code in the component implementations. It probably isn't what you're looking for, but it's included to highlight its differences from the others, and should still be used when possible.
#Module public interface MySqlModule {
#Binds UserStore bindUserStore(MySqlUserStore mySqlUserStore);
}
#Module public interface RedisModule {
#Binds UserStore bindUserStore(RedisUserStore redisUserStore);
}
#Component(modules = {MySqlModule.class, OtherModule.class})
public interface MySqlServerComponent { Server server(); }
#Component(modules = {RedisModule.class, OtherModule.class})
public interface RedisServerComponent { Server server(); }
Subclassing Modules
Create a subclass of your Module with different behavior. This precludes you from using #Binds or static/final #Provides methods, causes your #Provides method to take (and generate code for) unnecessary extra dependencies, and requires you to explicitly make and update constructor calls as dependencies may change. Due to its fragility and optimization opportunity-cost, I wouldn't recommend this option in most cases, but it can be handy for limited cases like substituting dependency-light fakes in tests.
#Module public class UserStoreModule {
#Provides public abstract UserStore bindUserStore(Dep1 dep1, Dep2 dep2, Dep3 dep3);
}
public class MySqlUserStoreModule extends UserStoreModule {
#Override public UserStore bindUserStore(Dep1 dep1, Dep2 dep2, Dep3 dep3) {
return new MySqlUserStore(dep1, dep2);
}
}
public class RedisUserStoreModule extends UserStoreModule {
#Override public UserStore bindUserStore(Dep1 dep1, Dep2 dep2, Dep3 dep3) {
return new RedisUserStore(dep1, dep3);
}
}
DaggerServerComponent.builder()
.userStoreModule(
useRedis
? new RedisUserStoreModule()
: new MySqlUserStoreModule())
.build();
Of course, your Module could even delegate to an arbitrary external Provider<UserStore>, at which point it would become tantamount to a component dependency. If you use want to use Dagger to generate the Provider or Component you depend on, though, this technique won't help you other than to break your graph into smaller pieces.
Choose among multiple Providers
Wire up both types at compile time, and only use one at runtime. This requires Dagger to prepare injection code for all your options, but allows you to switch by providing a Module parameter, and even allows you to change which object is provided (if you use a mutable parameter or read a value out of the object graph). Note that you'll still have a slight bit more overhead than with #Binds, and Dagger will still generate code for your options' dependencies, but the selection process here is clear, efficient, and Proguard-friendly.
This is probably the best general solution, but not ideal for test implementations; it's generally frowned-upon to let test-specific code sneak into production. You'll want module overrides or separate components for that kind of case instead.
#Module public class UserStoreModule {
private final StoreType storeType;
UserStoreModule(StoreType storeType) { this.storeType = storeType; }
#Provides UserStore provideUserStore(
Provider<MySqlUserStore> mySqlProvider,
Provider<RedisUserStore> redisProvider,
Provider<FakeUserStore> fakeProvider) {
switch(storeType) {
case MYSQL: return mySqlProvider.get();
case REDIS: return redisProvider.get();
case FAKE: return fakeProvider.get(); // you probably don't want this in prod
}
throw new AssertionError("Unknown store type requested");
}
}
In summary
When you truly need to decide at runtime, inject multiple Providers and choose from there. If you only need to select at compile time or test time, you should use module overrides or separate Components.
I am trying to make my app better and code more maintainable using Dagger2 I caught general idea, but still cannot figure out how scopes are managed by Dagger2
I injected dagger into my project (sounds funny).
I created ApplicationComonent component and it works perfectly in my project.
Here is my code.
#Singleton
#Component(modules = {
ApplicationModule.class,
ThreadingModule.class,
NetworkModule.class,
DatabaseModule.class,
ServiceModule.class,
ParseModule.class,
PreferencesSessionModule.class})
public interface ApplicationComponent {
ActivityComponent activityComponent(ActivityModule activityModule);
void inject(BaseActivity baseActivity);
void inject(MainAppActivity mainAppActivity);
void inject(MyApplication application);
void inject(BaseFragment baseFragment);
void inject(MyService service);
void inject(RegistrationIntentService service);
}
I create my component instance in MyApplication class like this
private void initializeAndInjectComponent() {
mApplicationComponent =
DaggerApplicationComponent
.builder()
.threadingModule(new ThreadingModule(1))
.applicationModule(new ApplicationModule(this))
.networkModule(new NetworkModule(
MyService.API_SERVER_BASE_URL,
MyService.TIMEOUT))
.build();
mApplicationComponent.inject(this);
}
And I can obtain component in order to inject in in my Activities
MyApplication application = MyApplication.get(this);
application.getApplicationComponent().inject(this);
Everything works perfectly.
To add each method as well as module class is annotated with #Singleton scope, all modules related to the ApplicationComponent
Now I want to make dependencies better and I have seen a lot of examples with custom scopes like #PerActivity, #PerFragment. I have a lot of questions, but about this later.
So I created ActivityComponent
#PerActivity
#Subcomponent(
modules = {
NetworkServiceModule.class,
ActivityModule.class,
PermissionModule.class
})
public interface ActivityComponent {
Activity activity();
void inject(BaseActivity baseActivity);
}
All modules looks like this
#PerActivity
#Module
public class ActivityModule {
private Activity mActivity;
public ActivityModule(Activity activity) {
this.mActivity = activity;
}
#Provides
#PerActivity
Activity provideActivity() {
return this.mActivity;
}
}
I have following dependencies in my BaseActivity
// Dependencies from ApplicationComponent
#Inject
protected ApplicationSettingsManager mApplicationSettingsManager;
#Inject
protected ScheduledThreadPoolExecutor mPoolExecutor;
// Dependencies from ActivityComponent
#Inject
protected SpiceManager mSpiceManager;
#Inject
protected PermissionController mPermissionController;
And in my onCreate() method I am injecting as following
MyApplication application = MyApplication.get(this);
application.getApplicationComponent().activityComponent(new ActivityModule(this)).inject(this);
Before creating subcomponent ActivityComponent it was
MyApplication application = MyApplication.get(this);
application.getApplicationComponent().inject(this);
Now I got an error
Error:(34, 10) error: com.octo.android.robospice.SpiceManager cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
BaseActivity.mSpiceManager
[injected field of type: com.octo.android.robospice.SpiceManager mSpiceManager]
I cannot figure out where is problem, what I missed.
My questions about scopes in dagger2.
Everything but #Singleton is ignored by Dagger 2, am I right ?
I don't understand how life of component is managed ? I have only one idea
When you use #Singleton annotation dagger is creating object in some static pool that will exist during whole application lifecycle, and will be destroyed when JVM process (dalvik VM,ART) instance will be destroyed.
When you use any other annotation is just for you as developer to better maintain code, #PerActivity, #PerFragment is just custom annotation nothing more. And in case you place #PerFragment component in Application class it will live as long as Application lives. Am I right ?
So I understand this like this, if dagger finds #Singleton annotation it will add static reference to component when it is created first time and in case of any other annotation it won't hold reference to component.
I would be very grateful for any help with problems described above.
UPDATE
Thank you David Medenjak for great answer, I got much better understanding of Dagger2.
I have also just found the problem, as far as I am using separate Activity component now, I forgot about two lines in ApplicationComponent and change inejction in my MainActivity to ActivityComponent instead of ApplicationComponent, so for sure it couldn't resolve dependencies from subcomponent.
void inject(BaseActivity baseActivity);
void inject(MainAppActivity mainAppActivity);
Now everything works perfectly, I like Dagger2 and separated architecture.
A bit radical, but to simplify things:
All Scope annotations are nothing but syntactic sugar—including #Singleton.
Scopes mostly just provide compile time checks. Cyclic dependencies, or errors about things that you might have missed. #Singleton is just like any other scope, the only difference is that it is an already existing annotation and you don't have to create it yourself. You could just use #MySingleton instead.
[...] dagger is creating object in some static pool that will exists during whole application lifecycle
No. Dagger does nothing static. You have component objects. Those components hold your objects created by modules. If an object in a component has the scope of the component, it will only be created once in that exact component. If you decide to create 2 AppComponent objects, you will have 2 objects of each #Singleton annotated object, each within its component. This is why you should keep the reference to the component. Most implementations that I have seen or used hence keep their AppComponent within their Application. If you do this, you can use it like a singleton—it is still just a POJO.
[...]you place #PerFragment component in Application class it will live as long as Application lives.
Yes. As already covered by the paragraph above, it is just an object. Keep the reference, you keep the objects. Throw it away or create a new one and you have new objects (defined within in this component / scope). You should although not keep activity or fragment scoped components any place besides in activities or fragments respectively, since keeping them e.g. in your app component will most likely lead to a memory leak. (If it doesn't, you probably would not have needed the activity or fragment scope.)
if dagger finds #Singleton annotation it will add static reference to component when it is created first time and in case of any other annotation it won't hold reference to component.
Again, no. Nothing static. Plain old java objects. You can have multiple #Singleton components with their own objects, but you probably shouldn't (Although this is what makes instrumentation testing possible / easy—just swap components.)
Your mentioned error
SpiceManager cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
This means that the component you are trying to inject your object with can not find any way to produce or provide a SpiceManager. Make sure you provide it from your AppComponent or some other place, are not missing any annotations, etc.
I'm having a project based on Dagger 2 which consists of two modules. The core module includes some interfaces and some classes that have member injections declared for these interfaces.
The actual implementations of these interfaces are included in the second module which is an Android project. So, naturally the provide methods for these are included in the Android project.
Dagger will complain during compilation about not knowing how to inject these in the core module.
Any thoughts on how to achieve this without using constructor injections?
In short, I just tried this, and it works. Be sure to check the exact error messages and make sure you are providing these interfaces and #Inject annotations are present.
There is probably just some wrong named interface or a missing annotation. Following up is a full sample using your described architecture that is compiling just fine. The issue you are currently experiencing is probably the one described in the last part of this post. If possible, you should go with the first solution though and just add those annotations.
The library
For reproducability this sample has minimalist models. First, the interface needed by my class in the library module:
public interface MyInterface {
}
Here is my class that needs that interface. Make sure to declare it in the constructor and provide the #Inject annotation!
#MyScope // be sure to add scopes in your class if you use constructor injection!
public class MyClassUsingMyInterface {
private MyInterface mMyInterface;
#Inject
public MyClassUsingMyInterface(MyInterface myInterface) {
mMyInterface = myInterface;
}
}
The idea is that the interface will be implemented by the app using MyClassUsingMyInterface and provided by dagger. The code is nicely decoupled, and my awesome library with not so many features is complete.
The application
Here need to supply the actual coupling. This means to get MyClassUsingMyInterface we have to make sure we can supply MyInterface. Let's start with the module supplying that:
#Module
public class MyModule {
#Provides
MyInterface providesMyInterface() {
return new MyInterface() {
// my super awesome implementation. MIT license applies.
};
}
}
And to actually use this, we provide a component that can inject into MyTestInjectedClass that is going to need MyClassUsingMyInterface.
#Component(modules = MyModule.class)
public interface MyComponent {
void inject(MyTestInjectedClass testClass);
}
Now we have a way to provide the requested interface. We declared that interface needed by the library class in a constructor marked with #Inject. Now I want a class that requires my awesome library class to use. And I want to inject it with dagger.
public class MyTestInjectedClass {
#Inject
MyClassUsingMyInterface mMyClassUsingMyInterface;
void onStart() {
DaggerMyComponent.create().inject(this);
}
}
Now we hit compile...and dagger will create all the factories needed.
Inject Libraries you can not modify
To just provide the full scale of dagger, this sample could also have been without actual access to the source code of the library. If there is no #Inject annotation dagger will have a hard time creating the object. Notice the missing annotation:
public class MyClassUsingMyInterface {
private MyInterface mMyInterface;
public MyClassUsingMyInterface(MyInterface myInterface) {
mMyInterface = myInterface;
}
}
In that case we have to manually provide the class. The module would be needed to be modified like the following:
#Module
public class MyModule {
#Provides
MyInterface providesMyInterface() {
return new MyInterface() {
};
}
#Provides
MyClassUsingMyInterface providesMyClass(MyInterface myInterface) {
return new MyClassUsingMyInterface(myInterface);
}
}
This introduces more code for us to write, but will make those classes available that you can not modify.