Boon
Boon

Reputation: 1153

Dependency injection in Jenkins development

I'm working on an (existing) Jenkins plugin and would like to use dependency injection. Unfortunately, DI for Jenkins development is poorly documented. As far as I know Jenkins uses Google's Guice framework for DI. There is this Wiki page, but I'm a little puzzled about it: in existing Jenkins plugins that I've checked I don't see such calls to Guice, but I do see plenty of uses of the @Inject annotation. Futhermore, it bothers me that I would need to call Guice.createInjector(new MyModule()).injectMembers(this); inside every class where I want dependency injection, it seems like I'm littering my code.

How do I do dependency injection in Jenkins? For example, I have a simple interface "MyInterface" and an implementing class MyInterfaceImpl. In a third class I have the following:

class MyClass {
    private MyInterface obj;

    @Inject
    public MyClass(MyInterface obj) {
        this.obj = obj;
    }

    ...
}

Is there a mechanism in Jenkins to automatically construct such objects, or do I have to add that Guice injector code?

Upvotes: 5

Views: 1052

Answers (2)

Jesse Glick
Jesse Glick

Reputation: 25461

You should not need to touch Guice. Define an interface (extending ExtensionPoint as a matter of documentation); implement it as an @Extension; and look up implementations using ExtensionList. JenkinsRule-based tests can use @TestExtension to add mock implementations. Note that properly speaking this a service registry, not dependency injection.

Upvotes: 2

M.P. Korstanje
M.P. Korstanje

Reputation: 12039

The wiki with the incomplete information was written by Dan Alvizux as part of a SO question. It does not reflect how Jenkins actually does its DI.

The correct way to register a class for DI appears to be annotating it with @Extension and using @Inject as normally. There are some other options discussed in the JavaDoc.

Upvotes: 0

Related Questions