Replacing dependency throws error: > Cannot change resolution strategy of dependency configuration after it has been resolved

I want my task_2 to execute the task_1 but replace a dependency defined in task_2 instead of using the one defined in task_1.

  dependencies {
    implementation("junit:junit:4.12")
  }

tasks.register("task_1") {
  // code which generates a build and compileClasspath
}

tasks.register("task_2") {
  dependsOn(tasks.named("task_1"))
  doLast {
    configurations.all {
      resolutionStrategy {
        force(
          "junit:junit:4.12",
          "group:module:version",
        )
      }
    }
  }
}

Running task_2 I get the following error:

> Cannot change resolution strategy of dependency configuration ':compileClasspath' after it has been resolved.