4

I'm trying to adapt an Eclipse RCP 3.x application to use some facilities from e4. For this reason, there is no e4xmi file.

In particular, I need to get access to some services:

public class RunModeService {

@Inject
private static ECommandService commandService;
@Inject 
private static EHandlerService handlerService;

...
}

It would appear that if I instantiate the class myself (as I am doing) then none of the injection takes place.

Is it possible to get hold of these services another way? If so, I can begin to hook into e4 and DI, by creating a command whose handler is instantiated by the framework and in which injection occurs.

Balder
  • 8,623
  • 4
  • 39
  • 61
wrgrs
  • 2,467
  • 1
  • 19
  • 24

2 Answers2

3

If you have the IEclipseContext you can get objects using:

ECommandService commandService = eclipseContext.get(ECommandService.class);

IEclipseContext can be injected.

You can create your own objects using ContextInjectionFactory which will do DI on the object for your:

MyClasss myClass = ContextInjectionFactory.make(MyClass.class, eclipseContext);

or you can do injection on an existing class instance with:

ContextInjectionFactory.inject(myClass, eclipseContext);

In a view or editor you can get the Eclipse Context from the view / editor site using:

eclipseContext = ((PartSite)getSite()).getContext();

But PartSite is an internal class so it really should not be used.

greg-449
  • 109,219
  • 232
  • 102
  • 145
  • 1
    It seems that IEclipseContext needs to be injected as well. From this question, I got hold of the BundleContext and used that to get an IEclipseContext: http://stackoverflow.com/questions/18316970/how-to-get-the-ieclipsecontext-in-an-activator. However, my new context does not include an ECommandService, or indeed an MApplication. I wonder if the application model is not created if you've created an e3 app. – wrgrs Jun 02 '14 at 11:03
  • 1
    That context is the specialized OSGi service context and only contains OSGi services. You need the context from MApplication or an MPart. All Eclipse 4 applications are e4 under the hood, 3.x apps just have a lot of compatibility code on top of e4. – greg-449 Jun 02 '14 at 11:14
0

You can also manually inject your class with the active IEclipseContext:

IEclipseContext context = getActiveEclipseContext();
RunModeService service = ContextInjectionFactory.make(RunModeService.class, context);

To get the active IEclipseContext without DI, you can use the example code from this answer.

Community
  • 1
  • 1
Balder
  • 8,623
  • 4
  • 39
  • 61