我有一个不同的汽车对象,例如:
object Porsche extends Car with CarsUtilities {
override def start() {...}
override def canStart(fuelInLitr: Int) = fuelInLitr > 5
override val fuelInLitr = 45
override val carId = 1234567
}
这就是Car
和CarsUtilities
的样子:
trait Car {
def start(): Unit
val canStart(fuel: Double): Boolean
val fuelInLitr: Int
val carId: Int
}
trait CarsUtilities {
// method to prepare start() result
def prepareResult() = {...}
}
我有两个api服务:
class CarApiService (wsClient: WSClient, configuration: Configuration) {
def getCarkey(carId: String): Future[Option[CarKey]] = {
// here im performing api call using wsclient
}
}
和
class CarSupplierApiService @Inject()(configuration: Configuration) {
def getSupplierInfo(carId: String): Future[Option[SupplierInfo]] = // here im performing elastic search api call
}
现在,在一些汽车对象中,让我们说其中50%的人会使用这些api服务,有时两次和其他时间只使用其中一种。那些服务实例提供这些汽车对象的最佳做法是什么?
我真的不想使用new
为每个需要使用它们的对象创建它们的实例...所以我想也许可以懒惰地将它们添加到CarsUtilities
所以所有的汽车对象可以在需要时访问这些api服务......这会是一个很好的解决方案吗?
另外,如果我这样做,我如何给出配置和WSClient注入?
trait CarsUtilities {
lazy val carApiService = new CarApiService(???)
lazy val carSupplierApiService = new CarSupplierApiService(???)
// method to prepare start() result
def prepareResult() = {...}
}
谢谢!
使用playframework 2.6,scala 2.11.8:)
答案 0 :(得分:1)
通常,依赖注入和对象不能一起工作。请参阅here for work-arounds,但从长远来看,你想摆脱依赖注入类的对象。
您可能需要的是某种类型的业务服务,它可以注入控制器中,如下所示:
class CarsUtilities @Inject() (carApiService: CarApiService, carSupplierApiService: CarSupplierApiService) {
// this class implements all the business logic and can use the services
def prepareResult() = {}
}
在控制器中,您也可以注入此CarsUtilities
,因为依赖注入会“传播”。