Вопрос

I came across the dagger library from Square and I'm currently making some tests. I'm new to the DI principle so be kind :)

So, I understand Dagger can inject fields and constructors. I'm also aware that in my activities, I have to .inject(this); so that injection can be done at runtime. But what about an object O that needs to be created after the activity initialization ?

If O has injectable fields, I have to .inject(O); before using it otherwise I get a NullPointerException when accessing its injected variables. But if I write a injectable constructor, no problem, no runtime exception. Of course I wrote my @Module according to the documentation.

Isn't it the purpose of Dagger to injects fields with no other code to write ? Do I have to manually .inject(); all my objects ? There is for sure a thing I'm missing.

Thanks in advance.

Это было полезно?

Решение

As you wrote Dagger supports two kind of injection:

  • field injection
  • constructor injection

In the first case you create an object then you inject the fields using inject method. For example in your onCreate of an Activity you will call this:

mObjectGraph.inject(this);

The second type of injection (constructor injection) requires that the object is created by Dagger. You simply mark the constructor with @Inject annotation then you can create instance like this:

HasInjectableConstructor instance = mObjectGraph.get(HasInjectableConstructor.class);

That's it. Maybe Dagger 2 will change something in this matter: squ.re/dagger2

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top