Macwire可注射工厂 [英] Injectable factory with Macwire
问题描述
我正在淘汰MacWire进行依赖项注入。
I'm teasing out MacWire for dependency injection.
我发现对Guice有用的一件事是辅助注入,它可以自动连线工厂,这将帮助您创建需要运行参数的服务。
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.
Macwire是否有类似的东西?
Is there something similar with Macwire ?
推荐答案
可注入工厂是支持但不是MacWire的真正功能,而是按照MacWire的精神,您可以仅使用Scala。
Injectable factories are supported, but are not really a feature of MacWire, rather in MacWire's spirit, you can "just use Scala".
在这种情况下,可以使用函数类型。在Guice示例之后,假设您要创建由 startDate参数化的
和付款
:日期金额:金钱
。您可以定义一个依赖项:
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
它是正常依赖项:
class ServiceUsingPayment(paymentFactory: (Date, Money) => Payment)
val serviceUsingPayment = wire[ServiceUsingPayment]
您还可以使用类型别名来避免重复功能签名,并且在声明另一个服务的依赖项时使用该别名(如上面的 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
这篇关于Macwire可注射工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!