TaskHub.Shared

Core Response Architecture

The TaskHub.Shared.Response module provides a standardized way to return results from services, handlers, and APIs. It emphasizes clarity, type safety, and built-in telemetry.

Design Philosophy

The design is based on the Result Pattern, which avoids using exceptions for expected control flow (like validation errors or “not found” scenarios).

Core Components

  1. Result: The base class for all operation outcomes. It contains a ResultCode and a Message.
  2. **ValueResult**: Inherits from `Result` and adds a `Data` property of type `T`. Used when an operation returns a value.
  3. OpResult: A lightweight, internal-friendly record used for easy creation and implicit conversion to Result or ValueResult<T>.

Result and ValueResult

Result Class

public class Result
{
    public bool IsSuccess => ResultCode == 0;
    public int ResultCode { get; init; }
    public string Message { get; init; }
    
    // Implicit conversion from OpResult
    public static implicit operator Result(OpResult op) => new(op.ResultCode, op.Message);
}

ValueResult Class

public sealed class ValueResult<T> : Result
{
    public T? Data { get; init; }
    
    // Implicit conversion from OpResult
    public static implicit operator ValueResult<T>(OpResult op) => new(op.ResultCode, op.Message, default);
}

OpResult: The Adapter

OpResult is a helper that simplifies the syntax for returning results from methods.

public class OpResult(int code, string message)
{
    public bool IsSuccess => ResultCode == 0;
    public int ResultCode { get; init; } = code;
    public string Message { get; init; } = message;

    public TResult As<TResult>() where TResult : Result => (TResult)(Result)this;
}

How Implicit Conversions Work

Because Result and ValueResult<T> define implicit operators for OpResult, you can return an OpResult from a method that expects a Result:

public Result DoWork()
{
    if (failure) return new OpResult(1, "Failed");
    return new OpResult(0, "Success");
}

Telemetry & Diagnostics

Every time a Result or ValueResult<T> is instantiated, it automatically interacts with the current OpenTelemetry Activity.

Automatic Tags

Activity Status

If IsSuccess is true, the activity status is set to Ok. Otherwise, it is set to Error.