Using custom provider factories

Suppose that I am developing some utility classes that build upon ProviderFactory. Something like

abstract class MyProviderFactory @Inject constructor(private val providers: ProviderFactory) {
    fun which(tool: String): Provider<String> {
        // Do something with providers.exec() here - impl not important

The question is how I can use this MyProviderFactory that I have created - would I be obligated to use an ObjectFactory to explicitly create an object, or is it possible to have it be injected directly? It seems something like this:

abstract class MyTask @Inject constructor(private val objects: ObjectFactory): DefaultTask() {
    private val myProviders = objects.newInstance(
    // Rest of task goes here

seems to be a bit verbose and repetitive, but I’m not sure if

abstract class MyTask @Inject constructor(private val myProviders: MyProviderFactory): DefaultTask() {
    // Rest of task goes there

will actually do the same thing.

Any advice would be appreciated.

I don’t think you can inject an arbitrary class you implemented.
Just try it and see whether it works or not, but I don’t think so.
So yes, like you did it, you probably have to use the ObjectFactory to instantiate your factory.

But if I may suggest an alternative solution, if you can or do use Gradle 8.1, make your factory a shared build service.
Because those you can get injected easily since 8.1 using @ServiceReference. :slight_smile:

There are probably more ways to skin the cat, I suppose. If I had to only work with Kotlin code, I could possibly get away with something like

fun ProviderFactory.which(tool:String): Provider<String> { ... }

And just have a file full of this so it looks like ProviderFactory is giving this away for free, but that would make it look awkward for Groovy users.

Unfortunately, I don’t have Gradle 8.1 to make things easy and painless, but a shared build service for an object that has no real state is, however overkill, a distinct possibility.