Search code examples
javadependency-injectionrcpeclipse-rap

How can I add constructor params using Dependency Injection


I am trying to do the following. If possible I want to avoid creating them using the 'new' keyword, and rely on Dependency Injection. Is this possible given the following scenario?

public class One {

    @Inject
    private Two two;

    @PostConstruct
    public void createComposite(final Composite parent) {
        final Composite container = doSomethingWithParent(parent);

        // How do I call Twos constructor using injection and pass it the value for container?
        // new Two(context, container);
    }

}

@Creatable
@Singleton
public class Two
    @Inject
    public Two(final IEclipseContext context, final Composite containerFromOne) {
        context.set(Two.class.getName(), this);
        doSomethingImportantThatNeedsComposite(containerFromOne);
    }
}

public class Three
    @Inject
    private Two two;

    // I would like be able to use two anywhere in this class 
    // once two is instantiated by One    
}

I was also looking at the ContextInjectionFactory.make() but I don't see a way to pass in constructor arguments.


Solution

  • You can use ContextInjectFactory.make using the variant with two IEclipseContext parameters. The second IEclipseContext is a temporary context where you can put the extra parameters. Something like:

    IEclipseContext tempContext = EclipseContextFactory.create();
    
    tempContext.set(Composite.class, composite);
    
    // ... more parameters
    
    Two two = ContextInjectionFactory.make(Two.class, context, tempContext);
    

    Note: You don't use the @Creatable and @Singleton annotations with this.

    Once you have created it you can put it in to the Eclipse Context with:

    context.set(Two.class, two);
    

    Note that there can be several Eclipse Contexts. You may need to find the correct one.