简体   繁体   中英

Injectable factory with Macwire

I'm teasing out MacWire for dependency injection.

One thing that i found useful with Guice is the assisted inject, to autowire a factory that would help you to create some service that needs run parameters.

Is there something similar with Macwire ?

Injectable factories are supported, but are not really a feature of MacWire, rather in MacWire's spirit, you can "just use Scala".

In this case, you can use function types. Following the Guice examples, let's say you want to create a Payment parametrized by a startDate: Date and amount: Money . You could define a dependency:

val paymentFactory = (startDate: Date, amount: Money) => wire[Payment] 
                     // or create the payment in any other way

and then use it as a normal dependency:

class ServiceUsingPayment(paymentFactory: (Date, Money) => Payment)
val serviceUsingPayment = wire[ServiceUsingPayment]

You could also use a type alias to avoid repeating the function signature, and use that alias when declaring another service's dependencies (as in ServiceUsingPayment above):

type PaymentFactory = (Date, Money) => Payment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM