[英]Injectable factory with Macwire
I'm teasing out MacWire for dependency injection. 我正在挑逗MacWire的依赖注入。
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. 我发现Guice有用的一件事就是辅助注入,自动装配工厂,帮助你创建一些需要运行参数的服务。
Is there something similar with Macwire ? Macwire有类似的东西吗?
Injectable factories are supported, but are not really a feature of MacWire, rather in MacWire's spirit, you can "just use Scala". 支持可注射工厂,但实际上并不是MacWire的功能,而是MacWire的精神,你可以“只使用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
. 按照Guice示例,假设您要创建一个由
startDate: Date
参数化的Payment
startDate: Date
和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): 您还可以使用类型别名来避免重复函数签名,并在声明其他服务的依赖项时使用该别名(如上面的
ServiceUsingPayment
):
type PaymentFactory = (Date, Money) => Payment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.