Reputation: 4426
I have a controller :
public class MyController extends Controller {
private final AuthChecker authChecker;
@Inject
public MyController(AuthChecker authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}
And I have a problem with AuthChecker
because it keeps an internal state that is not reinitialized between each request. The initialization of this class is done in its constructor, which is executed only once whereas it is not a @Singleton
According to Play's documentation :
New instances are created every time a component is needed. If a component is used more than once, then, by default, multiple instances of the component will be created. If you only want a single instance of a component then you need to mark it as a singleton.
I want for every request to tell Guice to create a new instance. How can I solve this problem ?
Also, are controllers singletons ? Because they seem to be created only once in the whole application lifecycle.
Thanks.
Upvotes: 2
Views: 926
Reputation: 11993
You can use a Provider, meaning guice creates a new instance (if not configured otherwise in your module) everytime you access it:
public class MyController extends Controller {
private final Provider<AuthChecker> authChecker;
@Inject
public MyController(Provider<AuthChecker> authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker.get()
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}
Upvotes: 1