tags:

views:

21

answers:

1

Hi all,

I would like to have my own contexts for some CDI-based projects. I need (want) custom scopes so that I can isolate the how long a component lives and where.

To implement your own context, you need to implement the Context interface which is pretty self-explanatory, but how or where to you really define when it is created?

Thanks,

Walter

+1  A: 

I haven't tested this yet, but I believe this will work. For each custom scope/context you want in your application, you simply need to add that context via an extension when the container is initialized:

public void afterBeanDiscovery(@Observes AfterBeanDiscover afterBeanDiscovery, BeanManager beanManager)
{
  CustomContext customContext = new CustomContext();
  afterBeanDiscovery.addContext(customContext);

  beanManager ...
}

Now, the trick is, you need to hold a reference to that context so then when you want to start or stop it, you can. That would be something like:

@Inject
protected HttpRequestLifecycle httpRequestLifecycle;

public void doSomething()
{
  startContext();
  doStuff();
  stopContext();
}

public void startContext()
{
  httpRequestContextLifecycle.getHttpRequestContext().activate();
}

That should do it, there isn't a wealth of documentation out there, so I hope this helps.

Anyone interested, check out the source here: http://github.com/walterjwhite/server.web.application

Walter

Actually, this got me really close. Even after I start the context by setting it active, I am still getting the No Contexts Active for scope ...
Another note here - you cannot inject the context unless you make it a singleton. If it is application-scoped, you have no guarantee you'll get the same context that is in the contexts map. That means, the context you activate is a dummy context, it doesn't control anything. What I ended up doing was holding a reference to it in my lifecycle management classes and then injecting that lifecycle and getting the context.