https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
dagger
  • c

    Colton Idle

    11/03/2020, 4:04 AM
    Trying to parse this second sentence from the hilt guide on android docs: "Doing manual dependency injection requires you to construct every class and its dependencies by hand, and to use containers to reuse and manage dependencies." Is it just me or does the second half of that sentence not make sense?
    h
    • 2
    • 2
  • p

    Pablo

    11/04/2020, 1:07 PM
    Scenario I have an Activity called Activity1, then inside has a Fragment1 all have the
    @ContributeAndroidInjection
    and then if my Activity2 wants to inject Fragment1 Why I need to implement HasAndroidInjector and do the
    @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any>
    override fun androidInjector(): AndroidInjector<Any> = androidInjector
    to be able to use a Fragment that is already with
    @ContributeAndroidInjection
    ? If I remove this two lines it says :
    RunTimeException:Unable to resume activity {MyActivity}: java.lang.IllegalArgumentException: No injector factory bound for Class<MyClass>
    I thought that if I have this:
    @ContributesAndroidInjector(
     modules = [ FragmentProvider::class]
    )
    fun bindMyActivity2: Activity2
    It would work anyways, because I've add as a modules a module that has inside the
    @ContributesAndroidInjector
    with that Fragment... Is it because I need that `hasAndroidInjector`when I want to provide injection into a inner Fragment?
    c
    • 2
    • 1
  • c

    Colton Idle

    11/06/2020, 9:17 PM
    Yep. But dagger reflect has partial reflection or full reflection. I'm using full reflection.
    j
    • 2
    • 2
  • c

    coroutinedispatcher

    11/08/2020, 4:49 PM
    Anybody who can give me a hint on what I am doing wrong here? Using Hilt though https://stackoverflow.com/q/64739048/8914336
    a
    r
    • 3
    • 5
  • k

    Kshitij Patil

    11/20/2020, 8:38 AM
    Do I need to replace all `implementarion`s with `api`s for hilt to work properly in a multi-module project ? I don't have any feature modules and am trying to closely follow the way chrisbanes/tivi has been implemented but I'm getting "XYZ does not represent a declared type" error Link to my example implementation: https://github.com/Kshitij09/HiltMultiModuleExample
    w
    • 2
    • 1
  • c

    Colton Idle

    11/28/2020, 9:53 PM
    Is it possible to use hilt and have provision methods? I'm assuming since we don't create things like ApplicationComponent anymore, we don't actually have access to use provision methods anymore and we have to use field injection instead?
    a
    • 2
    • 2
  • b

    bodo

    12/02/2020, 12:50 PM
    Hi Dagger Experts. I have a common question about the annotation processor of dagger. my project is a multi module with a lot of features. and every feature has an activity (annotated with @AndroidEntryPoint). do i have to run annotation processing in every feature module
    kapt(...)
    another example is when i annotate a constructor of a class with @Inject in a library oder feature module, do i also have to run the annotation processor in each of this modules i am asking because then i have to run annotation processing in nearly every module which is not really performant
    a
    • 2
    • 2
  • c

    Christopher Elías

    12/10/2020, 2:21 PM
    Hello everyone 🖐️! Question, Im getting into a feature modularization architecture with pure dagger, no dagger-android, no hilt, just dagger. While my modules grow my application class is starting to look like this:
    class MyApp(): Application(), LoginComponentProvider, RegisterComponentProvider, RecoverPasswordComponentProvider  {
    
        // Reference to the application graph that is used across the whole app
        val appComponent by lazy {
            // Creates an instance of AppComponent using its Factory constructor
            // We pass the applicationContext that will be used as Context in the graph
            DaggerMyAppComponent.factory().create(applicationContext)
        }
    
        override fun provideLoginComponent(): LoginComponent {
            return appComponent
                .loginComponent()
                .create()
        }
    
        override fun provideRegisterComponent(): RegisterComponent {
            return appComponent
                .registerComponent()
                .create()
        }
    
        override fun provideRecoverPasswordComponent(): RecoverPasswordComponent {
            return appComponent
                .recoverPasswordComponent()
                .create()
        }
        ... On every new feature module I will have to implement its provider
    }
    Is any pattern or better way to improve this? Im doing this based on the official documentaton for dagger in android https://developer.android.com/training/dependency-injection/dagger-multi-module
    t
    • 2
    • 8
  • b

    blakelee

    12/23/2020, 1:40 AM
    Is it possible to create an annotation so that whenever I use that annotation it gives me an item. I'm trying to do something like this
    class MyClass @Inject constructor(
      @Tablet isTablet: Boolean
    )
    Then in my module I have something like
    @Provides
    @Tablet
    fun provideIsTablet(context: Context): Boolean = someWayToTellIfTablet
    Is there a way to create an annotation like this without have to use
    @Named("Tablet")
    n
    c
    j
    • 4
    • 5
  • c

    Colton Idle

    01/01/2021, 4:39 AM
    Looking at hilt docs and they say "*Predefined bindings* to represent Android classes such as 
    Application
     or 
    Activity
    ." Can anyone explain what that means? Edit: I think this is part of the lingo of dagger that I haven't picked up yet, but it seems like it's pretty widely accepting that "bindings" in the context of dagger means "types that are available to you". If so... Bindings for Application or Activity... do they actually mean Context?
    a
    • 2
    • 2
  • c

    Colton Idle

    01/03/2021, 2:05 AM
    Working with dagger on a larger team. What do you all do to ease "onboarding" of someone that is familiar with dagger but we have so many Types available to inject, it can be hard to find. Do you recommend just listing out what "bindings" are available? Or is there something else that's clever that I haven't thought of?
    h
    r
    • 3
    • 4
  • s

    Slackbot

    01/06/2021, 1:15 AM
    This message was deleted.
    r
    • 2
    • 1
  • n

    Nicholas Doglio

    01/12/2021, 1:20 AM
    Does anyone know what needs to be added to
    build.gradle
    file to enable kapt to work properly when using JDK 15 to build? I keep getting this error `package javax.annotation.processing does not exist import javax.annotation.processing.Generated`whenever I try to build. My config is the following:
    plugins {
        id 'com.android.application'
        id 'kotlin-android'
        id 'kotlin-kapt'
    }
    
    kapt {
        javacOptions {
            option("-source", "8")
            option("-target", "8")
        }
    }
    
    android {
        compileSdkVersion 30
        defaultConfig {
            applicationId "com.ndoglio.daggerkapt"
            minSdkVersion 23
            targetSdkVersion 30
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), '<http://proguard-rules.pro|proguard-rules.pro>'
            }
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
        kotlinOptions {
            jvmTarget = '1.8'
        }
    }
    
    dependencies {
        implementation 'androidx.core:core-ktx:1.3.2'
        implementation 'androidx.appcompat:appcompat:1.2.0'
        implementation 'com.google.android.material:material:1.2.1'
        implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    
        implementation 'com.google.dagger:dagger:2.30.1'
        kapt 'com.google.dagger:dagger-compiler:2.30.1'
    }
    r
    j
    j
    • 4
    • 11
  • m

    Manuel Vivo

    01/18/2021, 1:08 PM
    Thread about what’s new in Dagger/Hilt 2.31. Hope it helps 🙂 https://twitter.com/manuelvicnt/status/1351151438748123142
    👍 4
    c
    • 2
    • 1
  • m

    Massimo Carli

    01/23/2021, 4:31 PM
    Hi all. I'm trying a very simple example with an
    @AssistedInject
    class.
    class CalculatorImpl @AssistedInject constructor(
        private val logger: Logger,
        @Assisted private val increment: Int
    ) : Calculator {
    
      override fun addOne(a: Int) = a.inc().apply {
        logger.log("New value is $this")
      }
    }
    The
    @AssistedFactory
    is the following
    @AssistedFactory
    interface CalculatorImplFactory {
    
      fun create(
          inc: Int
      ): CalculatorImpl
    }
    When I try to inject the
    CalculatorImplFactory
    in an Activity like this
    @AndroidEntryPoint
    class MainActivity : AppCompatActivity() {
    
      @Inject
      lateinit var calculatorFactory: CalculatorImplFactory
      // ...
    }
    When I build I get a
    CalculatorImplFactory cannot be provided without an @Provides-annotated method.
    The documentations says that
    Dagger will create the implementation for the assisted factory and provide a binding for it.
    but this doesn't seem to be true. What am I missing? Thanks
    • 1
    • 1
  • t

    Tiago Nunes

    02/05/2021, 11:32 AM
    Hi everyone, I'm currently stuck in a "simple" use case using Hilt: I want a Retrofit service singleton, which takes an OkHttpClient. The OkHttpClient has an interceptor, which uses the Retrofit service singleton (to make a certain request inside the interceptor) The problem is: -> The OkHttpClient takes a Retrofit as argument -> The Retrofit takes an OkHttpClient as argument Cheers
    j
    a
    • 3
    • 7
  • c

    Colton Idle

    02/08/2021, 8:36 PM
    Getting an error between a Provider written in java, and an @inject written in Kotlin. I need to do field injection, and so I have
    @Inject var taxes: Taxes? = null
    Unfortunately it needs to be nullable as the provider is nullable, but I get an error saying Dagger does not support injection into private fields... which leads me to do
    @set:Inject var taxes: Taxes? = null
    and everything works. I could have sworn that this "workaround" wasn't needed for latest versions of dagger. Am I missing something?
    t
    • 2
    • 1
  • s

    Sinan Gunes

    02/15/2021, 12:43 PM
    What is the proper way to have a singleton while using assisted injection. I mean same
    @Assisted
    parameter should return same object.
    w
    • 2
    • 13
  • c

    Colton Idle

    02/18/2021, 3:11 PM
    Hello. I have a simple setup where I have my app and another gradle module. All of this works fine. Now I created a dagger module with a @Binds @IntoSet in both my app module and my other gradle module. But now, only the app modules @Binds @IntoSet gets loaded in my app, not the gradle modules. Is there something I'm missing here on how to get this second dagger module to be provided correctly?
    a
    • 2
    • 5
  • a

    Amrita Chaturvedi

    02/25/2021, 6:55 AM
    Hi, Does anyone here have experience or relevant resources for mocking dagger related dependencies while unit testing in a multi-module clean architecture-based project? Kinda stuck with it here. 😅
    a
    t
    j
    • 4
    • 20
  • m

    Manuel Vivo

    03/01/2021, 5:17 PM
    Hi everyone! Hilt is in Beta now 🚀 https://github.com/google/dagger/releases/tag/dagger-2.33
    :party-parrot: 1
    👍 14
    c
    • 2
    • 2
  • e

    escodro

    03/03/2021, 6:45 PM
    Hello, everyone! 😊 Is there any gotcha with Hilt + Instrumented Tests? I’m following the Hilt Testing documentation and the Crane sample and can’t make it work at all! If I run with
    --debug
    it only gives me the default:
    Execution failed for task ':app:kaptDebugAndroidTestKotlin'.
    > A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
    > java.lang.reflect.InvocationTargetException (no error message)
    I’m migrating from Koin to Hilt but this is blocking me once I want to do some end to end tests in my application. Thanks a lot in advance! ❤️
    w
    a
    t
    • 4
    • 10
  • l

    Lucien Guimaraes

    03/09/2021, 12:16 PM
    Hello 👋 Is there a Dagger way to provide a ViewModel to a Composable Screen ? I'm not using Hilt so I don't have the
    @HiltViewModel
    annotation. How would you achieve it only with Dagger ?
    c
    a
    a
    • 4
    • 7
  • j

    Jason Ankers

    03/15/2021, 2:49 AM
    Is it permitted to write extension methods/properties on a custom component? I.e im using this to reduce the verbosity of accessing an entrypoint.
    val AuthenticatedComponent.entryPoint: AuthenticatedComponentEntryPoint
        get(): AuthenticatedComponentEntryPoint {
            return EntryPoints.get(this, AuthenticatedComponentEntryPoint::class.java)
        }
    And then I can inject with:
    private val myRepository = authManager.component!!.entryPoint.getMyRepository()
    Edit: Just realized EntryPoints are specific to Hilt and this is a dagger channel
    j
    • 2
    • 4
  • m

    miqbaldc

    03/15/2021, 4:46 AM
    Is it possible to use 
    @ApplicationContext
     in DFM (dynamic feature module)? or should we provide application context manually? If we need to provide manually in DFM, is there any reference you guys can point me out?
    DFM - error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ApplicationContext android.content.Context cannot be provided without an @Provides-annotated method.
    opened an issue here: https://github.com/google/dagger/issues/2477
    f
    • 2
    • 2
  • k

    knthmn

    03/15/2021, 9:37 AM
    I have a class that can be constructor injected, however if I want to install it in a specific component a also scope it, should I put it in a module and
    @Provides
    it?
    f
    • 2
    • 3
  • a

    André Thiele

    03/20/2021, 5:17 PM
    Do I need to include dependencies inside the :app module that are provided as @ Singleton from another module? https://stackoverflow.com/questions/66724358/do-i-need-to-include-dependencies-inside-the-app-module-that-are-provided-as-s
    j
    j
    • 3
    • 5
  • f

    FunkyMuse

    03/22/2021, 10:35 PM
    Dagger2 is hard, but it can be easy, part 4 - Singleton is a lie
    p
    • 2
    • 5
  • a

    André Thiele

    04/04/2021, 8:39 AM
    How scope a database to a logged in user using Hilt? The problem is that a database should also be kind of singleton scoped but also scoped to a new user when logging out and in.
    ➕ 1
    c
    j
    c
    • 4
    • 26
  • s

    Slackbot

    04/09/2021, 7:15 AM
    This message was deleted.
    ➕ 1
    c
    p
    +2
    • 5
    • 6
Powered by Linen
Title
s

Slackbot

04/09/2021, 7:15 AM
This message was deleted.
➕ 1
c

Colton Idle

04/09/2021, 9:57 AM
Although I'm in the same boat (just started using hilt and multi modules last week) I haven't integrated DI into the other modules yet... But you didn't really ask a question... do you have anything specific?
☝️ 2
p

Pavel Sidyakin

04/09/2021, 11:27 AM
In my current project, we do not use dagger outside modules. I.e. we use dagger internally only in modules. Outside modules only usual interfaces are available. For module gluing we use Component Holder pattern. Further reading: https://proandroiddev.com/modularization-of-android-applications-in-2021-a79a590d5e5b Example: https://github.com/PavelSidyakin/WeatherForecast
j

Jeremy

04/09/2021, 11:44 PM
Yes we use dagger in multi module, we just migrated to Hilt, previously just using subcomponents. Do you have a specific question or issue?
componentholder looks fine but there is more boilerplate
a

amirhosen.ebrahimi

04/11/2021, 12:24 PM
I use dagger in my multi module project . my module is daynamic feature . it is too hard
j

Jeremy

04/12/2021, 11:04 PM
My main confusion w/ dagger espec. in multi module is every app/team does it very different. I think that is the main sales pitch of hilt
View count: 5