Search code examples
javadependency-injectioneclipse-rcpe4

How to inject IEventBroker into a class not defined in Application Model of Eclipse RCP application?


I have two classes, class A and class B. A is a class for displaying Part in RCP application, which is defined in Application Model. B is a customized class for retrieve data, and whenever the data changed, it should notify class A to update relevant UI. I've asked a question here about how to make these two classes coordinate. However now the problem is that since B is not defined in Application Model, so it returns null whenever I call eventBroker.post() in class B.

What I've tried is the following way when I invoke class B:

B b = new B();
ContextInjectionFactory.inject(b,IEclipseContext);
b.execute();

I don't know how to get IEclipseContext which is not defined in the above code though, since the above code is not executed in a class defined in Application Model. I'd really appreciate that if anyone can shed a light on this problem.


Solution

  • You really have to start from somewhere which the injection system does know about and create all the intermediate classes using the injection system.

    This might be a something like a command handler where you can use ContextInjectionFactory.make or ContextInjectionFactory.inject to create/inject the classes. There are several other ways to get classes created with injection but they all require you to start from something that the application model knows about.

    For classes which you want to be available throughout the application creating them in the application LifeCycle class is another possible place which is known about by the application model.

    Alternatively you can use the OSGi service context which can be accessed with:

    BundleContext bundleContext = ... your plugin's bundle context
    
    IEclipseContext serviceContext = EclipseContextFactory.getServiceContext(bundleContext);
    

    This context has very limited contents but does include the event broker.