dev@hk2.java.net

HK2 on OSGi

From: Martin Soch <martin.soch_at_oracle.com>
Date: Fri, 17 Jan 2014 09:34:34 +0100

Hello HK2 developers,

I am evaluating HK2 and I am experiencing troubles with named services
when running in OSGi environment.
I would like to dynamically create named services with the following
code snippet:

     public EventService getEventService(String name) {
         EventService es = locator.getService(EventService.class, name);
         if (es == null) {
             // there is no service in the registry with given name ->
create it
             DynamicConfigurationService dcs =
locator.getService(DynamicConfigurationService.class);
             DynamicConfiguration config = dcs.createDynamicConfiguration();
             Descriptor d = createEventServiceDescriptor(name);
             config.bind(d);
             config.commit();
             es = locator.getService(EventService.class, name);
         }
         return es;
     }

     private Descriptor createEventServiceDescriptor(String name) {
         return BuilderHelper.link(EventServiceImpl.class).
                 to(EventService.class).
                 named(name).
                 in(Singleton.class).
                 build();
     }

"EventService" is the interface/contract and the "EventServiceImpl" is
the implementation of that interface.
The getEventService(String) works fine when running as standalone Java
application but in OSGi environment it always returns "null".

Under OSGi I am using hk2-osgi-adapter to obtain the ServiceLocator with
the following code:

Main main = (Main) bundleContext.getService((ServiceReference)
bundleContext.getServiceReference(Main.class));
ModulesRegistry registry = (ModulesRegistry)
bundleContext.getService((ServiceReference)
bundleContext.getServiceReference(ModulesRegistry.class));
StartupContext ctx = new StartupContext();
ServiceLocator l = main.createServiceLocator(registry, ctx, null, null);

where ModulesRegistry means com.sun.enterprise.module.ModulesRegistry,
Main means com.sun.enterprise.module.bootstrap.Main and bundleContext is
instance of org.osgi.framework.BundleContext.

Do you have any idea why I am always getting null under OSGi ?
I am using ProSyst implementation of OSGi and HK2-2.2.0-b27 from Maven repo.

Thanks
Martin