Scala Guice - 用mixin注入

时间:2017-06-12 14:08:34

标签: scala dependency-injection playframework guice

是否可以先实例化依赖关系,然后将其绑定到模块config方法中?

目前我有以下配置:

class PersonServiceImpl @Inject()(addressService: AddressService) {
  ...
}

class AppModule extends AbstractModule with ScalaModule { 

  def configure() {
    bind[PersonService].to[PersonServiceImpl]
    bind[AddressBook].to[AddressBookImpl]
  }

  @Provides @Singleton
  def provideAddressService(addressBook: AddressBook): AddressService = {
    new AddressServiceImpl(addressBook) with SecureAddressView
  }

}

......工作正常。我现在要做的是将AddressServiceImpl的实例化移动到一个单独的模块中。所以,问题是为了创建AddressServiceImpl的实例,我需要Guice为我注入addressBook参数,但我也想自己创建实例,所以我可以将SecureAddressView混合在: / p>

class AddressModule extends AbstractModule with ScalaModule { 

  def configure() {
    bind[AddressService].to[AddressServiceImpl]
  }

  @Provides @Singleton
  def provideAddressService(addressBook: AddressBook): AddressService = {
    new AddressServiceImpl(addressBook) with SecureAddressView
  }

}

然而,这失败了,因为Guice回来抱怨provideAddressService方法。它基本上表示A binding to AddressService was already configured并指向bind[AddressService].to[AddressServiceImpl]方法中的configure行。

任何想法如何创建一个实例并混合在一个特征中,同时仍然将下游参数依赖的解析权委托给Guice?

1 个答案:

答案 0 :(得分:0)

好的,非常明显的一个,但我被我必须覆盖configure方法的事实误导了。所以,我所要做的就是为configure提供一个虚拟实现。

class AddressModule extends AbstractModule with ScalaModule { 

  override def configure(): Unit = ()

  @Provides @Singleton
  def provideAddressService(addressBook: AddressBook): AddressService = {
    new AddressServiceImpl(addressBook) with SecureAddressView
  }

}

虽然这看起来仍然很狡猾,因为我必须明确地向AddressService构造函数提供所有参数。必须有一种更优雅的混合特性方式。或许不是......