Hi Kodeiners, :wave: (Shared module) I have multi...
# kodein
a
Hi Kodeiners, đź‘‹ (Shared module) I have multi-module backend architecture and created an HttpClient as singleton as below:
Copy code
bindSingleton() { HttpClient(CIO) }
(Auth module) then I set authentication token to the header using the singleton instance
Copy code
val client: HttpClient by closestDI().instance()
 client.config {
            defaultRequest {
                headers.append(HttpHeaders.Authorization, "$schemes $token")
            }
(User module) Also, I have http clients that talk to each other in microservices. But it looks like I can’t set auth token to the same instance, no token is set in the header for the client below.
Copy code
private val client: HttpClient by instance()
Kodein: 7.11.0 WDYT? Any suggestion?
r
client.config { }
return a new instance of
HttpClient
, so you will need to manage a new instance in your Auth module, or you could replace your singleton by a factory/multiton depending on a generic config that could carry your auth.
👍 1
a
🤦‍♂️ thank you, I’ll try to change it to multiton
@romainbsl I’ve changed it to multiton but now it says “No binding found for HttpClient on context UserClientImpl”, I didn’t have the error when it was singleton. Here is my multiton binding:
Copy code
fun Application.service(test: Boolean) = DI.Module("service") {
    bindMultiton<String, HttpClient> { token -> createHttpClient(!test, token) }
...
}

fun createHttpClient(consul: Boolean, token: String) = HttpClient(CIO) {
...
 defaultRequest {
    headers.append(HttpHeaders.Authorization, "Bearer $token")
    }
and I set token in my auth module as
Copy code
closestDI().instance<String, HttpClient>(arg = token)
here is my userClient module
Copy code
val userClient
    get() = DI.Module("userClient") {
        bind<UserClient>() with singleton { UserClientImpl(di) }
    }
and this is how I call the instance:
Copy code
class UserClientImpl(
    override val di: DI
) : DIAware, UserClient {

    private val client: HttpClient by instance()
...
}
r
this code does not “update” to your client instance: closestDI().instance<String, HttpClient>(arg = token)
What you should do is private val client: HttpClient by instance(arg = token) thus DI will create an instance of your HttpClient with the given token
that being said, you should consider using http client interceptor to fulfil your request with such information like tokens / headers and so on