Dependency Injection to Play Framework 2.5 modules

試著忘記壹切 提交于 2021-02-10 07:58:05

问题


I have a module class with the following signature:

class SilhouetteModule extends AbstractModule with ScalaModule {

I would like to inject configuration:

class SilhouetteModule @Inject() (configuration: Configuration) extends AbstractModule with ScalaModule {

But it fails with the following error.

No valid constructors
Module [modules.SilhouetteModule] cannot be instantiated.

The Play documentation mentions that

In most cases, if you need to access Configuration when you create a component, you should inject the Configuration object into the component itself or...

, but I can't figure out how to do it successfully. So the question is, how do I inject a dependency into a module class in Play 2.5?


回答1:


There are two solutions to solve your problem.

First one (and the more straight forward one): Do not extend the com.google.inject.AbstractModule. Instead use the play.api.inject.Module. Extending that forces you to override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]]. Within that method you could do all your bindings and you get the configuration inserted as a method-parameter.

Second one (and the more flexible one): Depending on your needs of the components you want to inject, you could define a provider for the component you want to bind. In that provider you could inject whatever you want. E.g.

import com.google.inject.Provider

class MyComponentProvider @Inject()(configuration:Configuration) extends Provider[MyComponent] {
    override def get(): MyComponent = {
        //do what ever you like to do with the configuration
        // return an instance of MyComponent
    }
}

Then you could bind your component within your module:

class SilhouetteModule extends AbstractModule {
    override def configure(): Unit = {
        bind(classOf[MyComponent]).toProvider(classOf[MyComponentProvider])
    }
}

The advantage of the second version, is that you are able to inject what ever you like. In the first version you get "just" the configuration.




回答2:


Change your constructor signature from:

class SilhouetteModule @Inject() (configuration: Configuration) extends AbstractModule with ScalaModule

to:

class SilhouetteModule(env: Environment, configuration: Configuration) extends AbstractModule with ScalaModule

see here for more info: https://github.com/playframework/playframework/issues/8474



来源:https://stackoverflow.com/questions/39863190/dependency-injection-to-play-framework-2-5-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!