2016-09-19 71 views
0

我正在使用Scala + Play和Guice设置用于依赖注入的开箱即用。我也在幕后使用Akka Persistence,并希望为自定义阅读日志创建一个绑定,然后我可以在我的应用程序中注入它。如何创建一个相关的Guice(Play/Scala)绑定?

不幸的是,读杂志的构造方法(我不控制)需要明确提到男主角系统:

PersistenceQuery(actorSystem).readJournalFor[CustomReadJournal]("custom-key") 

如何从绑定定义类中去的根本actorSystem参考( Module)?这可能吗?更一般地,是可以定义相互依存的绑定(一拉Scaldi?)

Module类条目目前的样子:提前

bind(classOf[CustomReadJournal]).toInstance(PersistenceQuery(<what do i put here?>).readJournalFor[CustomReadJournal]("custom-journal")) 

感谢您的帮助!

+0

你是否已经使用@Provides和提供你的actorSystem作为参数,以便你可以注入?如果您需要提供另一个,则可以使用play.api.libs.concurrent.Akka.system(Play.current)中内置的akka​​系统进行播放。 – EdgeCaseBerg

回答

1

如果您需要执行某种逻辑来创建依赖注入,则使用@Provides注释很有用。例如:

trait MyProvider { 
    @Provides 
    def provideThing(): Thing = { 
    //make the thing and return it 
    } 
} 
class MyModule extends AbstractModule with MyProvider { 
    override def configure() { 
    bind(classOf[TraitYYY]).to(classOf[ClassThatTakesThingAsParameter]) 
    } 
} 

知道一个有用的东西是@Provides方法可以自己带参数,并得到他们的论点注入。例如:

@Provides 
def provideThingNeedingParameter(param: P): ThingNeedingParam = { 
    new ThingNeedingParam(param) 
} 

这是有关你的情况,我相信,因为你要提供演员系统的一些类的一个实例。

// You can use @Singleton with @Provides if you need this to be one as well! 
@Provides 
def provideActorSystem(app: Application): ActorSystem = { 
    play.api.libs.concurrent.Akka.system(app) 
} 

@Provides 
def providePersistenceQuery(actorSystem: ActorSystem): PersistenceQuery = { 
    PersistenceQuery(actorSystem) 
} 

@Provides 
def provideCustomReadJournal(persistenceQuery: PersistenceQuery):CustomReadJournal = { 
    persistenceQuery.readJournalFor[CustomReadJournal]("custom-key")  
} 

通过创建一个@Provides注释方法你CustomReadJournal可以避免配置bind通话完全和控制参数多一点。另外,如果您需要,@Provides可以使用@Singleton。我没有使用Akka持久性,但我认为这应该对你有所帮助

相关问题