Search code examples
scalaplayframeworkguice

Create class with Injectable Parameters


Consider the following class:

class MongoDumpBuilder (recordingId: String, parquetService: ParquetService) {
...
}

I want to inject the parquetService, the problem is that I want to create MongoDumpBuilder as follows:

NOTE: I want to pass recordingId.stringify to the class

new MongoDumpBuilder(recordingId.stringify)
        .withPacificEvents(pacificEvents)
        .withAssets(assets)
        .withTransactions(transactions)
        .withReports(reports)
        .withExpenses(expenses)
        .build()

But this will work only with:

new MongoDumpBuilder(recordingId.stringify, parquetService)

If i will do MongoDumpBuilder with Inject i cannot create it

class MongoDumpBuilder @Inject()(recordingId: String, parquetService: ParquetService) {
???
}

Any ideas how to solve it?


Solution

  • You can use naming in order to bind recordingId. Add this to your Module:

    bind(classOf[String]).annotatedWith(Names.named("recordingId")).toInstance(recordingId.stringify)
    

    Then define your class:

    class MongoDumpBuilder @Inject()(@Named("recordingId") val recordingId: String, parquetService: ParquetService) {
    ...
    }