Is it possible to obtain a CDI conversation
instance programatically only knowing that the current thread
is the one being used to process the CDI request
associated with the wanted conversation? And if possible then how?
In particular, what I want to do is this:
@ConversationScoped
public class UnitOfWork {...}
public class Client {
@Inject transient UnitOfWork uof;
...
}
public class Room {
@Inject transient UnitOfWork uof;
...
}
but using a programatic mechanism to initialize the uof
instance variables instead of applying the @Inject annotation (because Client
and Room
are entities and they doesn't support injection).
I already tryed to inject the UnitOfWork
by means of a BeanManager
obtained by the following static method:
public static <B> B getManagedBean(Class<B> type, Annotation... qualifiers) {
try {
BeanManager beanManager = InitialContext.doLookup("java:comp/BeanManager");
Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);
Bean<B> bean = (Bean<B>) beanManager.resolve(beans);
CreationalContext<B> cc = beanManager.createCreationalContext(bean);
return bean.create(cc);
} catch (NamingException e) {
throw new RuntimeException("", e);
}
}
but the problem is that beans given by means of the above method are new ones (every call gives a new instance), and I need that Client
and Room
share the same conversation scoped instance of UnitOfWork
.