glassfish-hk2
glassfish-hk2 copied to clipboard
How to mix two sopes?
I have a Jersey application and use RequestScope (for connection). Also, I have a separate thread with my custom Scope. How to mix bindings? I usually get an error connection that is not in the request scope.
bindFactory(ConnectionFactory.class)
.to(Connection.class)
.proxy(true)
.proxyForSameScope(false)
.in(RequestScoped.class);
bindFactory(ConnectionFactory.class)
.to(Connection.class)
.proxy(true)
.proxyForSameScope(false)
.in(MyScope.class);
....
@Service
@Singleton
public class MyService {
@Inject
OperationManager opManager;
@Inject
ScopedService service;
private <T> T runInScope(Callable<T> task) {
T result;
try (OperationHandle<MyScope> connectionOp = opManager
.createOperation(MyScopeImpl.INSTANCE)) {
connectionOp.resume();
try {
result = task.call();
} catch (Exception e) {
throw new Exception("Error in the scope", e);
} finally {
connectionOp.suspend();
}
}
return result;
}
public void doSomething() {
runInScope(() -> service.getValues());
}
}
@MyScope
@Service
class ScopedService {
@Inject
AnotherService service; // connection belongs to requet scope, however I expect new
}
```