I am trying to understand Components in Dagger 2. Here is an example:
@Component(modules = { MyModule.class })
public interface MyComponent {
void inject(InjectionSite injectionSite);
Foo foo();
Bar bar();
}
I understand what the void inject()
methods do. But I don't understand what the other Foo foo()
getter methods do. What is the purpose of these other methods?
Dagger generates code similar to what you would have written manually. Internally, Dagger creates a graph of objects that it can reference to find the way to provide an instance of a class. For every class in the graph, Dagger generates a factory-type class that it uses internally to get instances of that type.
The term dependency injection context is typically used to describe the set of objects which can be injected. In Dagger 2, classes annotated with @Module are responsible for providing objects which can be injected. Such classes can define methods annotated with @Provides .
Modules are a way of telling Dagger how to provide dependencies from the dependency graph. These are typically high level dependencies that you aren't already contributing to the dependency graph through the @Inject constructor annotation we discussed in our previous article.
Reusability is one of the many attributes that are said to contribute to a high quality code base. Dagger is in many aspects a tool which helps a lot with writing reusable code.
In the context of a hierarchy of dependent components, such as in this example, provision methods such as Foo foo()
are for exposing bindings to a dependent component. "Expose" means "make available" or even "publish". Note that the name of the method itself is actually irrelevant. Some programmers choose to name these methods Foo exposeFoo()
to make the method name reflect its purpose.
Explanation:
When you write a component in Dagger 2, you group together modules containing @Provides
methods. These @Provides
methods can be thought of as "bindings" in that they associate an abstraction (e.g., a type) with a concrete way of resolving that type. With that in mind, the Foo foo()
methods make the Component able to expose its binding for Foo
to dependent components.
Example:
Let's say Foo
is an application Singleton and we want to use it as a dependency for instances of DependsOnFoo
but inside a component with narrower scope. If we write a naive @Provides
method inside one of the modules of MyDependentComponent
then we will get a new instance. Instead, we can write this:
@PerFragment
@Component(dependencies = {MyComponent.class }
modules = { MyDependentModule.class })
public class MyDependentComponent {
void inject(MyFragment frag);
}
And the module:
@Module
public class MyDepedentModule {
@Provides
@PerFragment
DependsOnFoo dependsOnFoo(Foo foo) {
return new DependsOnFoo(foo);
}
}
Assume also that the injection site for DependentComponent
contains DependsOnFoo
:
public class MyFragment extends Fragment {
@Inject DependsOnFoo dependsOnFoo
}
Note that MyDependentComponent
only knows about the module MyDependentModule
. Through that module, it knows it can provide DependsOnFoo
using an instance of Foo
, but it doesn't know how to provide Foo
by itself. This happens despite MyDependentComponent
being a dependent component of MyComponent
. The Foo foo()
method in MyComponent
allows the dependent component MyDependentComponent
to use MyComponent
's binding for Foo
to inject DependsOnFoo
. Without this Foo foo()
method, the compilation will fail.
Let's say we would like to obtain instances of Foo
without having to call inject(this)
. The Foo foo()
method inside the component will allow this much the same way you can call getInstance()
with Guice's Injector
or Castle Windsor's Resolve
. The illustration is as below:
public void fooConsumer() {
DaggerMyComponent component = DaggerMyComponent.builder.build();
Foo foo = component.foo();
}
Dagger is a way of wiring up graphs of objects and their dependencies. As an alternative to calling constructors directly, you obtain instances by requesting them from Dagger, or by supplying an object that you'd like to have injected with Dagger-created instances.
Let's make a coffee shop, that depends on a Provider<Coffee>
and a CashRegister. Assume that you have those wired up within a module (maybe to LightRoastCoffee and DefaultCashRegister implementations).
public class CoffeeShop {
private final Provider<Coffee> coffeeProvider;
private final CashRegister register;
@Inject
public CoffeeShop(Provider<Coffee> coffeeProvider, CashRegister register) {
this.coffeeProvider = coffeeProvider;
this.register = register;
}
public void serve(Person person) {
cashRegister.takeMoneyFrom(person);
person.accept(coffeeProvider.get());
}
}
Now you need to get an instance of that CoffeeShop, but it only has a two-parameter constructor with its dependencies. So how do you do that? Simple: You tell Dagger to make a factory method available on the Component instance it generates.
@Component(modules = {/* ... */})
public interface CoffeeShopComponent {
CoffeeShop getCoffeeShop();
void inject(CoffeeService serviceToInject); // to be discussed below
}
When you call getCoffeeShop
, Dagger creates the Provider<Coffee>
to supply LightRoastCoffee, creates the DefaultCashRegister, supplies them to the Coffeeshop constructor, and returns you the result. Congratulations, you are the proud owner of a fully-wired-up coffeeshop.
Now, all of this is an alternative to void
injection methods, which take an already-created instance and inject into it:
public class CoffeeService extends SomeFrameworkService {
@Inject CoffeeShop coffeeShop;
@Override public void initialize() {
// Before injection, your coffeeShop field is null.
DaggerCoffeeShopComponent.create().inject(this);
// Dagger inspects CoffeeService at compile time, so at runtime it can reach
// in and set the fields.
}
@Override public void alternativeInitialize() {
// The above is equivalent to this, though:
coffeeShop = DaggerCoffeeShopComponent.create().getCoffeeShop();
}
}
So, there you have it: Two different styles, both of which give you access to fully-injected graphs of objects without listing or caring about exactly which dependencies they need. You can prefer one or the other, or prefer factory methods for the top-level and members injection for Android or Service use-cases, or any other sort of mix and match.
(Note: Beyond their use as entry points into your object graph, no-arg getters known as provision methods are also useful for exposing bindings for component dependencies, as David Rawson describes in the other answer.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With