Gary Ewan Park Gary Ewan Park - 4 months ago 10
C# Question

How can I utilize global variables within the `WithCriteria` of my Cake Tasks?

I have a number of tasks that use WithCriteria to specify when that Task should be run. That criteria is established in the main

Setup
method of the Cake script. However, when executing the script, I get a null reference exception...

enter image description here

As you an see, the Paths property is null, even though within my
Setup
method I am settings that property.

Why is this?

How can I utilize global variables within my
WithCriteria
?

Answer

The issue you're having is because with WithCriteria overload you're using the criteria is evaluated before the task is executed.

In general this is fine with constants / state created before task are executed.

With WithCriteria has two overloads the one you're using above

public static CakeTaskBuilder<T> WithCriteria(
       this CakeTaskBuilder<T> builder,
       bool criteria
)

As it takes a bool it's evaluated as the tasks created, which won't work if state is created & changed during setup or previous tasks, to solve this change you code to use the below overload

public static CakeTaskBuilder<T> WithCriteria(
       this CakeTaskBuilder<T> builder,
       Func<bool> criteria
)

This over load takes a Func<bool> criteria which is evaluated just before the task is executed, thus has access to any state created or modified before the task is executed.

So the fix for your issue is just to add ()=> before your criteria and it'll be lazy loaded like this:

Task("Test-NUnit")
    .WithCriteria(()=>DirectoryExists(parameters.Paths.Directories.NUnitTestResults))
    .Does(()=>
{
});