im creating a highly modular application, i have a lot of clases that need to be injected, all of them are childs (not direct childs) of the same class, none of them have constructor parameters.
I want to avoid having to create a "#Provides" method for each one of them in my module.
Is there a way to tell dagger to automatically provide all the classes that implement a base interface? Or is it possible to do it myself using reflection?
Im using dagger-android with kotlin
Update: Ill post some code to illustrate
In one of the modules i have this interface
interface ExampleClass: BaseExample {
fun doSomething()
}
}
Then in the main app i implement it
class ExampleClassImpl #Inject constructor() : ExampleClass {
override fun doSomething(){
}
}
The class where i need it is a Viewmodel created with dagger so inject works on the constructor.
class ExampleViewModel #Inject constructor(val exmpl :ExampleClass) : BaseViewModel {
}
I want to inject that ExampleClassImpl, to do that i need to create a #module with a method annotated with #Provides or #Bind and return that class.
Without the provider i get an error at compile time:
error: [Dagger/MissingBinding] com.myapp.ExampleClassImpl cannot be provided without an #Provides-annotated method.
You want to inject ExampleClass, but Dagger only knows about ExampleClassImpl. How would Dagger know that you want that specific subclass?
Moreover, you say you have many subclasses that you want to inject. How would Dagger know which one to provide to a constructor expecting the base class?
If you want ExampleViewModel to get an instance of ExampleClassImpl then you can simply change the declaration to:
class ExampleViewModel #Inject constructor(val exmpl :ExampleClassImpl)
Doing so you lose the ability to swap the constructor argument with a different implementation of ExampleClass.
The alternative is to have one #Named #Provides method per subclass. So something like:
// In your module
#Provides
#Named("impl1")
fun provideExampleClassImpl1(impl: ExampleClassImpl): ExampleClass = impl
// When using the named dependency
class ExampleViewModel #Inject constructor(#Named("impl1") val exmpl :ExampleClass)
Related
I need a solution where i could inject Fragment arguments/extras (one Longand one String to be specific) into Fragment's viewmodel and based on these values viewmodel could run it's setup in init {..}
All the ViewModel's injections are fine, dependencies in ViewModel's #Inject construct([dependencies]){..} are provided and working correctly.
My SubComponent looks like this at the moment :
`
#Scope
annotation class MyFragmentScope
#MyFragmentScope
#Subcomponent(modules = [MyFragmentModule::class])
interface MyFragmentSubcomponent : Injector<MyFragment> {
#Subcomponent.Builder
interface Builder : Injector.Factory<MyFragment>
}
#Module
abstract class MyFragmentModule {
#Binds
#IntoMap
#MyFragmentScope
#ViewModelKey(MyFragmentViewModel::class)
abstract fun bindMyFragmentViewModel(
viewModel: MyFragmentViewModel
): ViewModel
}
`
I would be super thankful for any support
Cheers
I tried to create a new ViewModelFactory with additional parameter, but sadly that didn't work out
Tried to use Hilt or Assisted Injection, which also didn't work out since my project is strictly restricted to Dagger v 2.16, if i try to update - tons of bugs arise from this old codebase, it would take months rewriting everything.
Maybe i just did something wrong
I've a question about implementing bindings per activity. Let me give you background. In application I've for ex. two activities, both of them inject same simple provider with two different values. When I create two separate modules for both activities with #ActivityRetainedComponent scope - compiler gives me error that there are duplicated bindings. The solution for that problem is to create special scope for multiple activities but then I'll need to manually point which scope should be used. I rather to make that pointing on DI level. Below some sample code:
class SampleProvider(
var text : String
)
#Qualifier
#Retention(AnnotationRetention.RUNTIME)
annotation class ActivityOneScope
#Qualifier
#Retention(AnnotationRetention.RUNTIME)
annotation class ActivityTwoScope
#InstallIn(ActivityRetainedComponent::class)
#Module
object ActivityOneModule {
#Provides
#ActivityOneScope
#ActivityRetainedComponent
fun provideSampleProvider() : SampleProvider = SampleProvider("ActivityOne")
}
#InstallIn(ActivityRetainedComponent::class)
#Module
object ActivityTwoModule {
#Provides
#ActivityTwoScope
#ActivityRetainedComponent
fun provideSampleProvider() : SampleProvider = SampleProvider("ActivityTwo")
}
I want to omit specifying scope during injection inside activity like this:
#ActivityOneScope
#Inject lateinit var testProvider: TestProvider
Is it possible in Hilt? In Dagger 2 it was possible using for example #ContributesAndroidInject and pointing specific module.
Thanks in advance
Whats the difference between #Inject and #Provide ?
although both are used for providing dependencies then whats the difference ?
This is covered very well in documentation, #Inject and #Provides are two different ways of introducing dependencies in the dependency graph. they are suited for different use cases
#Inject
Easy to use, simply add #Inject on constructor or property and you are done
It can be used to inject types as well as type properties
In a subjective way it may seem clearer than #Provides to some people
#Provides
If you don't have access to source code of the type that you want to inject then you can't mark its constructor with #Inject
In some situations you may want to configure an object before you introduce it in dependency graph, this is not an option with #Inject
Sometimes you want to introduce an Interface as a dependency, for this you can create a method annotated with #Provides which returns Inteface type
Following are the examples of above three points for #Provides
If you can't access source code of a type
// You can't mark constructor of String with #Inject but you can use #Provides
#Provides
fun provideString(): String {
return "Hello World"
}
Configure an object before introducing in the dependency graph
#Provides
fun provideCar(): Car {
val car = Car()
// Do some configuration before introducing it in graph, you can't do this with #Inject
car.setMaxSpeed(100)
car.fillFuel()
return car
}
Inject interface types in dependency graph
interface Logger { fun log() }
class DiscLogger : Logger{ override fun log() { } }
class MemoryLogger : Logger { override fun log() { } }
#Provides
fun provideLogger(): Logger {
val logger = DiscLogger() \\ or MemoryLogger()
return logger
}
#Inject:- It is used to inject dependencies in class.
#provides:- Required to annotated the method with #provide where actual instance is created.
This has covered in Dagger-2 documentation clearly.
What #Inject can Do:
Use #Inject to annotate the constructor that Dagger should use to
create instances of a class. When a new instance is requested, Dagger
will obtain the required parameters values and invoke this
constructor.
If your class has #Inject-annotated fields but no #Inject-annotated
constructor, Dagger will inject those fields if requested, but will
not create new instances. Add a no-argument constructor with the
#Inject annotation to indicate that Dagger may create instances as
well.
Similarly dagger can create for methods also.
Classes that lack #Inject annotations cannot be constructed by
Dagger.
What #Inject can't Do: and can be used #Provides annotation
Interfaces can’t be constructed.
Third-party classes can’t be annotated.
Configurable objects must be configured!
I have a class that is dagger injected via the constructor. However I now need to add an argument to this constructor that is not provided via injection and is instead a run time argument.
In my previous job, we rolled our own DI so I am not up to speed with all the "magic" annotations that dagger offers yet. I figured it should be simple to add an argument to a constructor and still have dagger inject the remaining values (as it was very simple to do with the aforementioned "roll your own DI" solution I have implemented before).
However, it looks like this is not possible with dagger (i.e. assisted injection). So I have been reading on how to solve this issue but have become completely stumped.
Here is the class that I am currently (successfully) injecting ServiceA into:
class Foo #Inject constructor(private val serviceA: ServiceA) {
...
}
What I would like to do is add another argument to this constructor that will be provided at run time. In this case a simple flag to determine some behaviour in the class. And, given that Dagger doesn't support assisted injection, I need to remove injection from Foo and instead create a FooFactory to handle creation of Foo objects. This factory will have ServiceA injected into its constructor and will provide a method to construct an instance of Foo taking the boolean. I will then end up with a Foo class that looks like:
class Foo(private val serviceA: ServiceA, myNewArgument: Boolean) {
...
}
And a FooFactory that looks like:
#Singleton
class FooFactory #Inject constructor(private val serviceA: ServiceA) {
fun createFoo(myNewArgument: Boolean) {
return Foo(serviceA, myNewArgument)
}
}
And, although this is a complete mess to just get an extra constructor arg, it does the job.
The problem I am facing, is that my Foo class is actually an AndroidViewModel, and will need to be constructed through the ViewModelProvider.Factory contract, which has a create method which is invoked by the SDK to create the view model. You override this method to create an instance of the view model but the method has no parameters, so there is no way to propagate the flag into the view model through this method.
So the only way for me to get the flag propagated to the view models constructor is by having the factory itself take the flag as an argument to it's constructor, which, because dagger does not support assisted injection, is not possible.
So, instead I am planning to make dagger manually inject my dependencies into the FooFactory at initialization time. This is where I am stuck, I cannot figure out how on earth to get dagger to manually inject dependencies into my class.
My FooFactory now looks like:
class FooFactory(private val myNewArgument: Boolean) : ViewModelProvider.Factory {
init {
// I need to trigger injection here... how though???
}
#Inject
lateinit var serviceA: ServiceA
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return Foo(
serviceA,
myNewArgument
) as T
}
}
So, somehow in the init block of the factory, I need to ask dagger to inject the fields annotated with #Inject. But I have no idea how to do this, I have tried following the answers at the following questions and tutorials:
https://proandroiddev.com/from-dagger-components-to-manual-dependency-injection-110015abe6e0
Dagger 2 - injecting non Android classes
Dagger 2 injection in non Activity Java class
None of these seem to work for my use case and I'm starting to lose it. Could anyone point me in the right direction? Is this dagger framework massively over engineered/complicated for not much benefit (this is the conclusion I am coming to at this point, all I want to do is achieve DI for testing purposes, I don't want to have to write factories so I can add an extra argument to a constructor)...
I have large Android ViewModel classes that tend to have a lot of dependencies (most of them are DAOs from Room, one per SQLite table). Some have more than 10 dependencies.
This is fine but the #Inject constructor is bloated with arguments, and contains only boilerplate code to set the injected members from the constructor arguments.
I wanted to switch to "regular" injected members, identified individually with an #Inject annotation, like other (dumb) classes.
This fails for Android related classes (although ViewModels are advertised as non-Android dependent, e.g. they don't use the Android framework) such as activities and fragments.
The workaround for that is to use a factory, which is injected from the Application class using the nice HasActivityInjector, HasServiceInjector, etc. interfaces.
Dagger doesn't provide any HasViewModelInjector, so if I persist in injecting members individually instead of injecting the constructor, here's what I'm given:
error: [dagger.android.AndroidInjector.inject(T)] XXXViewModel cannot be provided without an #Inject constructor or from an #Provides-annotated method. This type supports members injection but cannot be implicitly provided.
If I create a module that has a #Provides annotation to create the ViewModel, this doesn't inject individual members.
Did I miss something (my last sentence is what's most important in my question) or is it simply not possible to inject members, and I have to inject the constructor?
A bit of code.
What I want:
class MyViewModel extends ViewModel {
#Inject
MyDao myDao;
}
versus what I need to do:
class MyViewModel extends ViewModel {
private final MyDao myDao;
#Inject
MyViewModel(MyDao myDao) {
this.myDao = myDao;
}
}
First block of code (what I want) requires this method in a module:
#Provides
MyViewModel provideMyViewModel() {
return new MyViewModel();
}
but in this case the myDao field is null. How to inject the #Inject-annotated members?
I want to avoid the use of the 2nd block of code, which tends to create a huge constructor bloated with many arguments, should I need to inject a lot of members.
There are multiple ways of injection and I think you are referring to field injection. Field injection, unlike constructor injection, must be triggered manually. To do that, define a method in your component with the view model as parameter.
void inject(ViewModel viewModel)
And then call this method from your view model constructor perhaps.
class MyViewModel extends ViewModel {
private final MyDao myDao;
#Inject
MyDao myDao;
public MyViewModel() {
MyComponent mycomponent = DaggerMyComponent.....
myComponent.inject(this);
}
}