2

I have the following class :

class ClassWithInjectedConstructor @Inject constructor(private val simpleInjectedObject: SimpleInjectedObject) : ClassWhichThisInheritsFrom() {

    override fun check(): int {

        val result = simpleInjectedObject.methodToCall() // Returns an int.

        return 1;
    }
}

Please ignore that this function doesn't do anything except return the value on 1.

I am trying to get a handle on how the hell I work with this class, and it's injected constructor.

In my main application class (This class is java, not kotlin), I need to use the class above... and this is how I am trying to do it :

final ClassWithInjectedConstructor instance = new ClassWithInjectedInstructor();

I am aware that I need to pass something into that constructor, but how? If it is injected, do I need some fancy syntax?

MickeyThreeSheds
  • 986
  • 4
  • 23
  • 42

1 Answers1

4

Constructor injection with Dagger means that Dagger will create the object by calling the constructor and pass all the dependencies in for you. So when you call new Something() you're effectively not making use of constructor injection. You're simply creating an object.

All you really have to do is add the @Inject annotation on the constructor. That way Dagger knows about your class and if all of its dependencies can be provided Dagger can also provide that class. That's really all you need to do and when you want to use the class somewhere else you just have to request it.

  • If using field injection (e.g. in your Activity) you can just add an annotated field and Dagger will inject it along with all the other dependencies

    @Inject lateinit var something: Something
    
    fun onCreate(..) { activityComponent.inject(this) }
    
  • If using it in yet another class, you can just add it to the constructor...using constructor injection again...

    class OtherThing @Inject constructor(val something : Something)
    
  • Or add a provision method to your component and "request" it later...

    @Component interface MyComponent {
      fun provideSomething : Something
    }
    
    // ...
    
    val something : Something = myComponent.provideSomething()
    

If in your example SimpleInjectedObject can not be provided by Dagger, e.g. it does not use constructor injection and you did not add a @Provides annotated method that can provide it to any of your modules, you will get a build error stating that SimpleInjectedObject cannot be provided... about which you can find more information here.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134
  • What if there are some fields that Dagger can provide and some fields that it can't, eg. object id or some dynamic data? Lets say a ViewModel takes some dynamic data model object but Dagger can provide the rest of its dependencies? Also, can this view model be injected in some activity then? – ashwin mahajan Jun 19 '19 at 18:59