9

I would like to know if the RequestScoped context is currently active in a method or not.

At the moment, here is what I do :

@Inject private BeanManager beanManager;

public boolean isRequestScopeActive() {
    try {
        if (beanManager.getContext(RequestScoped.class).isActive()) {
            return true;
        } else {
            return false;
        }
    } catch (final ContextNotActiveException e) {
        return false;
    }
}

I think it's a bit heavy to catch a ContextNotActiveException just to know if a scope is active or not.

Do you have any better way to know the state (active or not) of a context in CDI ?

Anthony O.
  • 22,041
  • 18
  • 107
  • 163
  • RequestScoped should pretty much always be active, unless you're doing something via an async event. What are you trying to do? – LightGuard Jul 16 '12 at 16:52
  • Yes I'm trying to detect that because potentially I'm in an async event or in a scheduled one... see https://issues.jboss.org/browse/SEAMPERSIST-78 – Anthony O. Jul 17 '12 at 08:15
  • In that case, what you have is probably the best solution – LightGuard Jul 17 '12 at 16:58

1 Answers1

6

No, the only option we have in CDI 1.0 is to catch the ContextNotActiveException.

Your solution should work.

This actually ends up being a problem because scope implementation is not available for injection.

E.g. You can't just @Inject RequestScopedContextImpl rq; and check the rq.isActive() method, because we don't have access to that class without knowing the implementation details of CDI itself.

Lincoln
  • 3,151
  • 17
  • 22