Preserve an ordered workflow through composition in C#
A Template Method normally keeps an algorithm's order in a base class while derived classes override selected steps. When a type already needs another base class, move the ordered operation into a separate object and pass the variable behavior into it.
The important contract is the order and failure behavior. Replacing inheritance with callbacks should not accidentally let a caller skip validation, invoke the operation twice or reenter the same workflow halfway through an import.
Run a workflow with one variable step
Use the .NET 10 SDK. Create a console project in a new directory, then replace Program.cs with the example below.
dotnet new console --framework net10.0
dotnet run
Run dotnet run after saving the replacement. No additional packages are required.
The example uses an Action because there is one synchronous step to supply. The workflow owns its begin, success and cleanup phases. The printed commit is a success marker, not a database transaction.
using System;
using System.Threading;
var workflow = new ImportWorkflow();
workflow.Run(() => Console.WriteLine("import"));
try {
workflow.Run(() => workflow.Run(() => Console.WriteLine("nested")));
} catch (InvalidOperationException) {
Console.WriteLine("Nested call rejected");
}
try {
workflow.Run(() => throw new FormatException("Invalid row."));
} catch (FormatException) {
Console.WriteLine("Import failure propagated");
}
workflow.Run(() => Console.WriteLine("retry"));
/// <summary>Owns one ordered import at a time while the caller supplies its variable step.</summary>
public sealed class ImportWorkflow {
private int _running;
public void Run(Action import) {
ArgumentNullException.ThrowIfNull(import);
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0)
throw new InvalidOperationException("An import is already running.");
try {
Console.WriteLine("begin");
import();
Console.WriteLine("commit");
} finally {
try {
Console.WriteLine("end");
} finally {
Volatile.Write(ref _running, 0);
}
}
}
}
Expected output:
begin
import
commit
end
begin
end
Nested call rejected
begin
end
Import failure propagated
begin
retry
commit
end
The nested call is rejected before another begin message. A failed import does not print commit, but still reaches end. The final retry succeeds, showing that cleanup releases the workflow's running state after failure.
Give sequencing one owner
Callers supply only the import step. They cannot choose whether the workflow performs cleanup or records successful completion. The workflow instance can be held as a field by a UI component or another class without occupying that class's inheritance slot.
Delegates provide a typed callable contract. When several related operations and shared state must travel together, use a small strategy interface instead. Avoid replacing one clear callback with a long list of optional actions whose valid ordering callers must reconstruct. See Microsoft's delegate guidance and interface guidance .
This design preserves the useful workflow property of Template Method, but the extension mechanism is composition. It does not require describing every callback design as inheritance-based Template Method.
Specify failure and reentrancy
Interlocked.CompareExchange admits one operation on this instance. A concurrent or nested call is rejected, rather than queued. That is a deliberate policy, not a universal concurrency solution. A lock is reentrant for its owning thread, so adding lock alone would not reject the nested call demonstrated here.
CompareExchange
makes the admission check and state change atomic.
The finally block restores the guard even when the callback throws. Its nested finally also releases the guard if the cleanup message fails. The example lets the callback exception propagate. For real cleanup that can throw, define whether to aggregate errors, preserve the original failure or report cleanup separately, because a finally exception can replace an exception already in flight.
Any acquired resource needs its own ownership and disposal rules. Decide when an acquisition has succeeded before attempting its release. A console message is not evidence that a file, database transaction or external process was rolled back.
Keep asynchronous work asynchronous
Do not pass an async lambda to this Action. That produces async void, allowing the workflow to print success and release its guard before asynchronous work finishes. An asynchronous variant should accept Func<CancellationToken, Task>, return Task and await the supplied operation inside its guarded try/finally.
Test the successful order, callback failure, repeated use and the chosen concurrent-call policy. These checks protect the original workflow contract while leaving its host type free to inherit from the base class it actually needs.
Source and further reading
This article revisits the problem raised in the following original posts. The explanation and examples here are newly written for .NET 10. A linked question supplies the motivation, rather than an author-attributed solution.
-
Herman Schoenfeld’s question
on “Template method pattern without inheritance”, licensed under
CC BY-SA 3.0
.



Author: Herman Schoenfeld