How to set a dependency with information from a plugin extension?

I have written a Gradle plugin that needs to add a dependency to the applied project with information (i.e. a version number) from its extension object.

My first approach was to write the following code in the apply method on the Plugin class:

project.with {
  dependencies {
    compile "com.example:somelibrary:${project.myextension.version}"
  }
}

In this case the library was always added to the project with the default value of the extension object, since the part got evaluated directly when it was executed, i.e. when the user applies the plugin - before he changed values in the extension object.

I solved the problem by placing the following snippet inside the apply method:

project.with {
  afterEvaluate {
    dependencies {
      compile "com.example:somelibrary:${project.myextension.version}"
    }
  }
}

Is this the right way to solve that problem? Is there a method to listen for changes at the extension object by the user? Or is there in general a method that will be executed at the end of the configuration phase, that should be used for that kind of stuff?

My question also has a second part, since I think those two problems belong strongly together:

I extended the Zip task (‘class ZipPlugin extends Zip’) and need to configure it by settings from the extension object of my plugin.

Same problem here, I cannot do this in the constructor of my class, because the extension object has not been modified there yet. I cannot do it in my ‘@TaskAction’ method, because it will run (as far as I tried) after the parent’s class method. So I currently solved it the same way: using the afterEvaluate method in the constructor to configure the Zip task.

Is there also a better way?

The checkstyleplugin also does something like this with the ‘beforeResolve’ method.

https://github.com/gradle/gradle/blob/master/subprojects/code-quality/src/main/groovy/org/gradle/api/plugins/quality/CheckstylePlugin.groovy