eclipse-ee4j / glassfish-hk2

Dynamic dependency injection framework

Home Page:https://eclipse-ee4j.github.io/glassfish-hk2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to mix two sopes?

kiril-me opened this issue · comments

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
}

```