Pipeline¶
Pipeline provides a fluent way to chain operations and handle results in a sequential manner.
Basic Usage¶
// Create a pipeline
var pipeline = ResultPipeline.Start(new { Id = 1 });
// Chain operations
var result = pipeline
.Map(x => x.Id)
.Validate(x => x > 0, ErrorCode.InvalidInput, "Id must be positive")
.Bind(x => Result<int>.Success(x * 2))
.OnSuccess(x => Console.WriteLine($"Result: {x}"))
.OnFailure(error => Console.WriteLine($"Error: {error}"))
.Catch(ex => Result<int>.Failure(ErrorCode.InternalError, ex.Message))
.Result;
Advanced Usage¶
Custom Pipeline¶
// Implement IPipeline
public class CustomPipeline<T> : IPipeline<T>
{
public IPipeline<T> Map<TResult>(Func<T, TResult> mapper)
{
// Custom implementation
}
public IPipeline<T> Bind<TResult>(Func<T, Result<TResult>> binder)
{
// Custom implementation
}
public IPipeline<T> Validate(Func<T, bool> predicate, ErrorCode code, string message)
{
// Custom implementation
}
public IPipeline<T> OnSuccess(Action<T> action)
{
// Custom implementation
}
public IPipeline<T> OnFailure(Action<Error> action)
{
// Custom implementation
}
public IPipeline<T> Catch(Func<Exception, Result<T>> handler)
{
// Custom implementation
}
public Result<T> Result { get; }
}
// Use custom pipeline
var customPipeline = new CustomPipeline<int>();
var result = customPipeline
.Map(x => x * 2)
.Result;
Pipeline Events¶
// Subscribe to pipeline events
pipeline.OnSuccess += (value) =>
Console.WriteLine($"Pipeline success: {value}");
pipeline.OnFailure += (error) =>
Console.WriteLine($"Pipeline failure: {error}");
pipeline.OnException += (exception) =>
Console.WriteLine($"Pipeline exception: {exception.Message}");
Best Practices¶
- Keep pipelines short and focused
- Use meaningful operation names
- Handle errors appropriately
- Implement proper logging
- Use async operations when needed
- Consider performance implications
- Test pipeline behavior
- Document pipeline flow