whats the difference between @Provide and @Inject in dagger2?

Viewed 336

Whats the difference between @Inject and @Provide ?

although both are used for providing dependencies then whats the difference ?

2 Answers

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

  1. Easy to use, simply add @Inject on constructor or property and you are done
  2. It can be used to inject types as well as type properties
  3. In a subjective way it may seem clearer than @Provides to some people

@Provides

  1. 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
  2. In some situations you may want to configure an object before you introduce it in dependency graph, this is not an option with @Inject
  3. 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.

Related