Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependencies in Gradle Plugin in Gradle recommended way?

I am writing a custom plugin and to test it, I want to inject mock implementations. It is not just for testing but from API perspective too, I want to inject different implementations depending on the context. I am currently using Gradle 2.6 and I understand that it supports some form of Dependency Injection. I do not want to use Spring/Guice/HK2 since Gradle itself supports it. However, I am not able to find any information how to inject dependencies using Gradle 2.6 APIs.

For eg:

 class CustomTask extends DefaultTask {

       private SomeInterface interface

       @Inject
       CustomTask(SomeInterface interface) {}

       @TaskAction
       public void executeTask() {
           interface.executeSomething()
       }
 }

So, essentially, I want to figure where to define bindings for different instances of SomeInterface and the mechanism to inject it into task or anywhere else like some custom classes.

like image 531
chauhraj Avatar asked Sep 11 '15 19:09

chauhraj


1 Answers

Since this question was not closed, some information might still be useful for whoever runs into it.

I do not want to use Spring/Guice/HK2 since Gradle itself supports it.

You might have already seen the relevant discussion on the gradle forum.
https://discuss.gradle.org/t/dependency-injection-in-gradle-plugins/6538

We are currently working on this. Dependency injection is already available for internal Gradle services, but I'm guess you are wanting to inject your own collaborators. Our dependency injection will support this at some point.

As usually with Gradle, we can check whatever is in the oven.
https://github.com/gradle/gradle/tree/bd4fb1c396a695d55aeba9bc37e164a488c0b882/design-docs

This design document can give you a look into what one of the core maintainers thought is a good way to approach the problem. While it is not complete, I consider it quite valuable.

Unfortunately the document (along with the complete folder) has been removed on Sep 20, 2017 with the following message:

This has turned into a graveyard for ideas. It only serves to confuse people at this point. We have found it more productive to either

  • use GitHub Epics and issues for smaller design questions
  • use Google Docs for larger topics (e.g. native publishing)

These documents quickly go out of date once a feature is implemented. They are not a replacement for good user and code documentation.

Many of the documents are about features that we never ended up implementing. Having those documents still around might lock us into a certain way of thinking about a problem. Instead we should have a fresh look at it when we actually want to start working on it.

like image 80
dbalakirev Avatar answered Oct 20 '22 00:10

dbalakirev