When to use Factory <T> instead of provider <T>

The Dagger documentation shows using a Provider<Filter> to get Filter instances, which seems to make sense.

I am writing a ListAdapter that creates instances of the views that I would like to introduce a dagger. I have a desire to introduce a Provider<ViewType> in my ListAdapter and call mViewProvider.get() to create views.

However, the dagger documentation says:

Injecting Provider<T> has the ability to create confusing code, and can be a designer scent objects with incorrect or improper structuring of your chart. Often you will want to use Factory<T> or Lazy<T> or rebuild the lifetime and structure of your code to be able to simply enter T

I see how I could use Factory, just as it would when using an auxiliary injection.

But what would be the benefit of using my own Factory<T> outweigh the use of the Dagger Provider<T> , given that I would have to write the former? A.

+6
source share
1 answer

Provider<T> has a very specific meaning in the system. This is a delegated constructor of a graph-driven object. Provider<T> has certain guarantees / behavior, and I usually recommend not introducing Provider<T> unless you are supporting some kind of deprecated situation requiring it.

Factory<T> is an example. FooFactory is more accurate because the goal of this is that you are not using manual factories, but instead use something like AutoFactory ( http://github.com/google/auto ) to create factories that create objects. Then you do not need to write your own, but AutoFactory was not yet created when these documents were written.

Ultimately, the reason lies primarily in code clarity and long-term maintenance. Using an instance of a dagger instance as a de facto Factory instance is possible, but limited, because it can only work with instances that have dependencies. It is not possible to maintain stack call dependencies without adding another scope or graph level. This fact in Guice often led people to use additional features for shoe racking dependencies in object instance (provision) dependencies, playing games with custom areas and composing their objects and layers graph in order to get some free code.

It was decided that (in the form of) Assisted-Injection and (in the dagger) AutoFactory was created - so that you could do a more semantically understandable thing that did not depend on internal frames, but automatically do it for you.

Do not use Provider<T> - this is an opinion. You can do this if you want, but this is not recommended. Instead, we recommend this solution as AutoFactory , to get better named types with an enhanced value in your system, which can support more flexible handling of the state of the call stack.

+8
source

All Articles