A complete .NET solution that implements functional processing of use cases using the Mediator pattern with advanced ExecutionResult error handling. This library provides a clean way to organize business logic into discrete, testable use cases with sophisticated dependency injection support and functional error handling patterns.
- Mediator Pattern: Clean separation between use case parameters and their implementations
- Dependency Injection: Full support for Microsoft.Extensions.DependencyInjection
- Automatic Registration: Use Scrutor to automatically discover and register use cases
- Advanced ExecutionResult Pattern: Functional approach with generic and non-generic variants
- Rich Error Handling: ExecutionError with multiple messages, error codes, and log levels
- Implicit Conversions: Seamless conversion between values and ExecutionResult
- Result Combination: Combine multiple ExecutionResult objects using the
+operator orCombine()method - Testable: Easy to unit test individual use cases with comprehensive error scenarios
- Production Ready: Logging integration, cancellation support, and behavior pipeline
- Execution Behaviors: Apply cross-cutting concerns globally or per-call (validation, logging, caching, transactions)
- Use Case Chaining: Fluent chain execution with result passing and chain-aware behavior support
Add the required packages to your project:
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package Microsoft.Extensions.Logging.Abstractions
dotnet add package ScrutorusingFunctionalUseCases;publicclassGreetUserUseCase:IUseCaseParameter<string>{publicstringName{get;}publicGreetUserUseCase(stringname){Name=name??thrownewArgumentNullException(nameof(name));}}usingFunctionalUseCases;publicclassGreetUserUseCaseHandler:IUseCase<GreetUserUseCase,string>{publicasyncTask<ExecutionResult<string>>ExecuteAsync(GreetUserUseCaseuseCaseParameter,CancellationTokencancellationToken=default){if(string.IsNullOrWhiteSpace(useCaseParameter.Name)){returnExecution.Failure<string>("Name cannot be empty");}vargreeting=$"Hello, {useCaseParameter.Name}!";returnExecution.Success(greeting);}}usingMicrosoft.Extensions.DependencyInjection;usingFunctionalUseCases;varservices=newServiceCollection();// Register all use cases from the assembly containing GreetUserUseCaseservices.AddUseCasesFromAssemblyContaining<GreetUserUseCase>();varserviceProvider=services.BuildServiceProvider();vardispatcher=serviceProvider.GetRequiredService<IUseCaseDispatcher>();varuseCaseParameter=newGreetUserUseCase("World");varresult=awaitdispatcher.ExecuteAsync(useCaseParameter);if(result.ExecutionSucceeded){Console.WriteLine(result.CheckedValue);// Output: Hello, World!}else{Console.WriteLine($"Error: {result.Error?.Message}");}Marker interface for use case parameters. All use case parameters should implement IUseCaseParameter<TResult>:
publicinterfaceIUseCaseParameter<outTResult>:IUseCaseParameter{}Located in: FunctionalUseCases/Interfaces/IUseCase.cs
Generic interface for use case implementations that process use case parameters:
publicinterfaceIUseCase<inTUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{Task<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,CancellationTokencancellationToken=default);}Located in: FunctionalUseCases/Interfaces/IUseCase.cs
Advanced functional result types that encapsulate success/failure with rich error information:
// Generic variantpublicrecordExecutionResult<T>(ExecutionError?Error=null):ExecutionResult(Error)whereT:notnull{publicboolExecutionSucceeded{get;}publicboolExecutionFailed{get;}publicTCheckedValue{get;}// Throws ExecutionException if failedpublicTGetValueOrThrow(string?exceptionMessage=null);publicTResultMatch<TResult>(Func<T,TResult>onSuccess,Func<ExecutionError,TResult>onFailure);publicExecutionResult<TResult>Map<TResult>(Func<T,TResult>map);publicExecutionResult<TResult>Bind<TResult>(Func<T,ExecutionResult<TResult>>bind);}// Non-generic variantpublicrecordExecutionResult(ExecutionError?Error=null){publicboolExecutionSucceeded{get;}publicboolExecutionFailed{get;}publicExecutionErrorCheckedError{get;}}// Factory methods via Execution classvarsuccess=Execution.Success("Hello World");varfailure=Execution.Failure<string>("Something went wrong");varfailureWithException=Execution.Failure<string>("Error message",exception);// Implicit conversionExecutionResult<string>result="Hello World";// Automatically creates success resultRich error information with support for multiple messages, error codes, and logging levels:
publicrecordExecutionError:ExecutionError<string>;publicrecordExecutionError<T>{publicstringMessage{get;}publicIList<T>Messages{get;set;}publicstring?ErrorCode{get;set;}publicLogLevelLogLevel{get;set;}publicException?Exception{get;set;}publicIDictionary<string,object?>Properties{get;set;}}Exceptions passed to Execution.Failure(...) remain available through
ExecutionError.Exception, including original type and stack trace.
Mediator that resolves and executes use cases:
publicinterfaceIUseCaseDispatcher{Task<ExecutionResult<TResult>>ExecuteAsync<TResult>(IUseCaseParameter<TResult>useCaseParameter,CancellationTokencancellationToken=default)whereTResult:notnull;}Located in: FunctionalUseCases/Interfaces/IUseCaseDispatcher.cs
Global execution behaviors allow you to implement cross-cutting concerns like logging, validation, caching, performance monitoring, and more. They wrap around all use case executions in a clean, composable way and are registered globally via dependency injection.
publicinterfaceIExecutionBehavior<inTUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{Task<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default);}Located in: FunctionalUseCases/Interfaces/IExecutionBehavior.cs
usingMicrosoft.Extensions.Logging;publicclassLoggingBehavior<TUseCaseParameter,TResult>:IExecutionBehavior<TUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{privatereadonlyILogger<LoggingBehavior<TUseCaseParameter,TResult>>_logger;publicLoggingBehavior(ILogger<LoggingBehavior<TUseCaseParameter,TResult>>logger){_logger=logger;}publicasyncTask<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default){varuseCaseParameterName=typeof(TUseCaseParameter).Name;_logger.LogInformation("Starting execution of use case: {UseCaseParameterName}",useCaseParameterName);varstopwatch=System.Diagnostics.Stopwatch.StartNew();try{varresult=awaitnext().ConfigureAwait(false);stopwatch.Stop();if(result.ExecutionSucceeded){_logger.LogInformation("Successfully executed use case: {UseCaseParameterName} in {ElapsedMilliseconds}ms",useCaseParameterName,stopwatch.ElapsedMilliseconds);}else{_logger.LogWarning("Use case execution failed: {UseCaseParameterName} in {ElapsedMilliseconds}ms. Error: {ErrorMessage}",useCaseParameterName,stopwatch.ElapsedMilliseconds,result.Error?.Message);}returnresult;}catch(Exceptionex){stopwatch.Stop();_logger.LogError(ex,"Exception occurred during use case execution: {UseCaseParameterName} in {ElapsedMilliseconds}ms",useCaseParameterName,stopwatch.ElapsedMilliseconds);returnExecution.Failure<TResult>($"Exception in LoggingBehavior: {ex.Message}",ex);}}}Global execution behaviors are NOT automatically registered when you call the registration extension methods. You must register them manually and they will be applied to all use case executions:
// Register use cases from assemblyservices.AddUseCasesFromAssemblyContaining<GreetUserUseCase>();// Register global execution behaviors manually - these apply to ALL use case executionsservices.AddScoped(typeof(IExecutionBehavior<,>),typeof(LoggingBehavior<,>));services.AddScoped(typeof(IExecutionBehavior<,>),typeof(TimingBehavior<,>));Global behaviors are executed in the order they are registered. Each behavior's ExecuteAsync is invoked once and receives the next delegate in the pipeline. Any code that runs before calling next() executes ahead of downstream steps, and any code that runs after awaiting next() executes after those steps complete:
Behavior 1 enters → Behavior 2 enters → Use Case Handler → Behavior 2 continues → Behavior 1 continues
Validation Behavior:
publicclassValidationBehavior<TUseCaseParameter,TResult>:IExecutionBehavior<TUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{publicasyncTask<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default){// Perform validation logicif(/* validation fails */){returnExecution.Failure<TResult>("Validation failed");}returnawaitnext().ConfigureAwait(false);}}Caching Behavior:
publicclassCachingBehavior<TUseCaseParameter,TResult>:IExecutionBehavior<TUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{privatereadonlyIMemoryCache_cache;publicasyncTask<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default){varcacheKey=$"{typeof(TUseCaseParameter).Name}_{useCaseParameter.GetHashCode()}";if(_cache.TryGetValue(cacheKey,outExecutionResult<TResult>cachedResult)){returncachedResult;}varresult=awaitnext().ConfigureAwait(false);if(result.ExecutionSucceeded){_cache.Set(cacheKey,result,TimeSpan.FromMinutes(5));}returnresult;}}Transaction Behavior:
publicclassTransactionBehavior<TUseCaseParameter,TResult>:IExecutionBehavior<TUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{privatereadonlyITransactionManager_transactionManager;privatereadonlyILogger<TransactionBehavior<TUseCaseParameter,TResult>>_logger;publicTransactionBehavior(ITransactionManagertransactionManager,ILogger<TransactionBehavior<TUseCaseParameter,TResult>>logger){_transactionManager=transactionManager;_logger=logger;}publicasyncTask<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default){ITransaction?transaction=null;try{// Begin transactiontransaction=await_transactionManager.BeginTransactionAsync(cancellationToken);// Execute the use casevarresult=awaitnext().ConfigureAwait(false);if(result.ExecutionSucceeded){// Commit transaction on successawaittransaction.CommitAsync(cancellationToken);}else{// Rollback transaction on failureawaittransaction.RollbackAsync(cancellationToken);}returnresult;}catch(Exceptionex){// Rollback transaction on exceptionif(transaction!=null){try{awaittransaction.RollbackAsync(cancellationToken);}catch(ExceptionrollbackEx){_logger.LogError(rollbackEx,"Failed to rollback transaction");// Don't throw rollback exception, preserve original exception}}returnExecution.Failure<TResult>($"Exception in TransactionBehavior: {ex.Message}",ex);}finally{// Ensure transaction is disposedtransaction?.Dispose();}}}To use the transaction behavior, implement the ITransactionManager interface for your specific database technology:
// Example Entity Framework implementationpublicclassEntityFrameworkTransactionManager:ITransactionManager{privatereadonlyDbContext_context;publicEntityFrameworkTransactionManager(DbContextcontext){_context=context;}publicasyncTask<ITransaction>BeginTransactionAsync(CancellationTokencancellationToken=default){vartransaction=await_context.Database.BeginTransactionAsync(cancellationToken);returnnewEntityFrameworkTransaction(transaction);}}publicclassEntityFrameworkTransaction:ITransaction{privatereadonlyIDbContextTransaction_transaction;publicEntityFrameworkTransaction(IDbContextTransactiontransaction){_transaction=transaction;}publicasyncTaskCommitAsync(CancellationTokencancellationToken=default){await_transaction.CommitAsync(cancellationToken);}publicasyncTaskRollbackAsync(CancellationTokencancellationToken=default){await_transaction.RollbackAsync(cancellationToken);}publicvoidDispose(){_transaction.Dispose();}}// Register the transaction behavior and managerservices.AddScoped<ITransactionManager,EntityFrameworkTransactionManager>();services.AddScoped(typeof(IExecutionBehavior<,>),typeof(TransactionBehavior<,>));Located in: FunctionalUseCases/TransactionBehavior.cs and FunctionalUseCases/Interfaces/ITransactionManager.cs
In addition to global behaviors that apply to all use case executions, the library provides a powerful fluent API for applying behaviors to specific use case executions or chains. This allows for fine-grained control over when and where behaviors are applied.
The system now supports two distinct behavior application patterns:
- Global Behaviors: Registered with dependency injection and applied to ALL use case executions
- Per-Call Behaviors: Applied to specific executions using the
WithBehavior()fluent API with open generic types
The WithBehavior() method allows you to apply behaviors to specific use case executions using open generic type definitions. This approach ensures behaviors remain cross-cutting concerns that work with any use case parameter and result types.
// Apply a transaction behavior to a specific use case executionvarresult=awaitdispatcher.WithBehavior(typeof(TransactionBehavior<,>)).ExecuteAsync(newMyUseCase("data"));// Apply multiple behaviors to the same executionvarresult=awaitdispatcher.WithBehavior(typeof(TransactionBehavior<,>)).WithBehavior(typeof(ValidationBehavior<,>)).ExecuteAsync(newMyUseCase("data"));// Use behavior instances instead of typesvarcustomBehavior=newCustomBehavior<MyUseCase,string>(someParameter);varresult=awaitdispatcher.WithBehavior(customBehavior).ExecuteAsync(newMyUseCase("data"));// Apply behavior to an entire use case chainvarresult=awaitdispatcher.StartWith(newFirstUseCase("initial")).WithBehavior(typeof(TransactionBehavior<,>)).Then(x =>newSecondUseCase(x.Id,x.Property)).Then(x =>newThirdUseCase(x.ProcessedData)).ExecuteAsync();// Apply multiple behaviors to a chainvarresult=awaitdispatcher.StartWith(newGetUserUseCase(userId)).WithBehavior(typeof(TransactionBehavior<,>)).WithBehavior(typeof(ValidationBehavior<,>)).Then(user =>newValidateUserUseCase(user)).Then(user =>newSendWelcomeEmailUseCase(user.Email,user.Name)).ExecuteAsync();// Behaviors can be added at any point in the chainvarresult=awaitdispatcher.StartWith(newFirstUseCase()).Then(x =>newSecondUseCase(x.Id)).WithBehavior(typeof(TransactionBehavior<,>)).Then(x =>newThirdUseCase(x.ProcessedData)).ExecuteAsync();The TransactionBehavior<TUseCaseParameter, TResult> is a sophisticated example of a chain-aware behavior that adapts its strategy based on the execution context:
- Single Use Case: Creates transaction at use case start → commits/rollbacks at use case end
- Chain Execution: Creates transaction at chain start → commits/rollbacks at chain end
- Automatic Detection: Uses
IExecutionScopeto determine context without user intervention
// Transaction per single use casevarresult=awaitdispatcher.WithBehavior(typeof(TransactionBehavior<,>)).ExecuteAsync(newCreateOrderUseCase(orderData));// Creates transaction → executes use case → commits/rollbacks transaction// Transaction per entire chainvarresult=awaitdispatcher.StartWith(newCreateOrderUseCase(orderData)).WithBehavior(typeof(TransactionBehavior<,>)).Then(order =>newReserveInventoryUseCase(order.Items)).Then(inventory =>newProcessPaymentUseCase(orderData.Payment)).Then(payment =>newSendConfirmationEmailUseCase(order.CustomerEmail)).ExecuteAsync();// Creates transaction → executes entire chain → commits/rollbacks transactionTo create behaviors that adapt to execution context, implement IScopedExecutionBehavior<TUseCaseParameter, TResult> instead of the base IExecutionBehavior<TUseCaseParameter, TResult>:
usingMicrosoft.Extensions.Logging;publicclassCustomTransactionBehavior<TUseCaseParameter,TResult>:ScopedExecutionBehavior<TUseCaseParameter,TResult>whereTUseCaseParameter:IUseCaseParameter<TResult>whereTResult:notnull{privatereadonlyITransactionManager_transactionManager;privatereadonlyILogger_logger;publicCustomTransactionBehavior(ITransactionManagertransactionManager,ILoggerlogger){_transactionManager=transactionManager;_logger=logger;}publicoverrideasyncTask<ExecutionResult<TResult>>ExecuteAsync(TUseCaseParameteruseCaseParameter,IExecutionScopescope,PipelineBehaviorDelegate<TResult>next,CancellationTokencancellationToken=default){if(scope.IsChainExecution){// Chain execution logicif(scope.IsChainStart){_logger.LogInformation("Starting transaction for chain {ChainId}",scope.ChainId);// Start transaction for entire chain}varresult=awaitnext().ConfigureAwait(false);if(scope.IsChainEnd){// Commit or rollback transaction at chain endif(result.ExecutionSucceeded){_logger.LogInformation("Committing transaction for chain {ChainId}",scope.ChainId);// Commit transaction}else{_logger.LogWarning("Rolling back transaction for chain {ChainId}",scope.ChainId);// Rollback transaction}}returnresult;}else{// Single use case execution logic_logger.LogInformation("Starting transaction for single use case");// Create transaction → execute → commit/rollbackvartransaction=await_transactionManager.BeginTransactionAsync(cancellationToken);try{varresult=awaitnext().ConfigureAwait(false);if(result.ExecutionSucceeded){awaittransaction.CommitAsync(cancellationToken);}else{awaittransaction.RollbackAsync(cancellationToken);}returnresult;}catch{awaittransaction.RollbackAsync(cancellationToken);throw;}finally{transaction.Dispose();}}}}The IExecutionScope interface provides context information to chain-aware behaviors:
publicinterfaceIExecutionScope{boolIsChainExecution{get;}// True if part of a use case chainboolIsChainStart{get;}// True if first use case in chainboolIsChainEnd{get;}// True if last use case in chainstring?ChainId{get;}// Unique identifier for the chain}Per-call behaviors are registered as open generic types and resolved at execution time based on the actual use case parameter and result types:
// Register behaviors as open generics for per-call usageservices.AddScoped(typeof(TransactionBehavior<,>));services.AddScoped(typeof(ValidationBehavior<,>));services.AddScoped(typeof(CachingBehavior<,>));// Register any dependencies they needservices.AddScoped<ITransactionManager,EntityFrameworkTransactionManager>();services.AddMemoryCache();// For caching behavior// Global behaviors are still registered the same wayservices.AddScoped(typeof(IExecutionBehavior<,>),typeof(LoggingBehavior<,>));- Selective Application: Apply expensive behaviors (like transactions) only where needed
- Chain-Aware Intelligence: Behaviors automatically adapt to single vs. chain execution
- Composition: Combine multiple per-call behaviors for specific scenarios
- Performance: Avoid overhead of global behaviors when not needed
- Flexibility: Mix global and per-call behaviors as appropriate
Scenario 1: E-commerce Order Processing
// Transaction behavior applied to entire order workflowvarresult=awaitdispatcher.StartWith(newValidateOrderUseCase(orderRequest)).WithBehavior(typeof(TransactionBehavior<,>)).Then(order =>newReserveInventoryUseCase(order.Items)).Then(reservation =>newProcessPaymentUseCase(reservation.OrderId,orderRequest.Payment)).Then(payment =>newCreateOrderUseCase(payment.OrderId,payment.Amount)).ExecuteAsync();// Single transaction spans the entire workflowScenario 2: Caching Expensive Queries
// Cache only expensive user profile queriesvarprofile=awaitdispatcher.WithBehavior(typeof(CachingBehavior<,>)).ExecuteAsync(newGetUserProfileUseCase(userId));// Regular user operations don't use cachingvarupdateResult=awaitdispatcher.ExecuteAsync(newUpdateUserNameUseCase(userId,newName));Scenario 3: Validation for Critical Operations
// Apply strict validation only to sensitive operationsvarresult=awaitdispatcher.WithBehavior(typeof(StrictValidationBehavior<,>)).WithBehavior(typeof(AuditLogBehavior<,>)).ExecuteAsync(newDeleteAccountUseCase(userId,confirmationToken));The library provides powerful use case chaining capabilities that allow you to compose multiple use cases into a sequential workflow. Results are automatically passed between use cases, and execution stops on the first failure.
// Chain multiple use cases with result passingvarresult=awaitdispatcher.StartWith(newGetUserUseCase(userId)).Then(user =>newValidateUserUseCase(user)).Then(user =>newSendWelcomeEmailUseCase(user.Email,user.Name)).ExecuteAsync();// Access the final resultif(result.ExecutionSucceeded){Console.WriteLine($"Welcome email sent: {result.CheckedValue}");}The Then() method automatically passes the result of the previous use case to the next:
varresult=awaitdispatcher.StartWith(newCreateUserUseCase("John","john@example.com")).Then(user =>newAssignRoleUseCase(user.Id,"StandardUser")).Then(userRole =>newSendActivationEmailUseCase(userRole.User.Email,userRole.ActivationToken)).Then(activation =>newLogUserCreationUseCase(activation.UserId,activation.Timestamp)).ExecuteAsync();// Each use case receives the .CheckedValue from the previous use case as its parameterChains stop execution on the first failure and provide comprehensive error handling:
varresult=awaitdispatcher.StartWith(newValidateInputUseCase(inputData)).Then(validInput =>newProcessDataUseCase(validInput)).Then(processedData =>newSaveDataUseCase(processedData)).OnError(error =>{// Handle any error that occurred in the chainlogger.LogError("Chain execution failed: {Error}",error.Message);returnTask.FromResult(Execution.Failure<SavedData>($"Processing failed: {error.Message}"));}).ExecuteAsync();// If any step fails, the OnError handler is called and subsequent steps are skippedChains work seamlessly with both global and per-call behaviors:
// Apply transaction behavior to entire chainvarresult=awaitdispatcher.StartWith(newBeginOrderUseCase(customerId)).WithBehavior(typeof(TransactionBehavior<,>)).Then(order =>newAddItemsUseCase(order.Id,items)).Then(order =>newCalculateTotalUseCase(order)).Then(order =>newProcessPaymentUseCase(order.Total,paymentInfo)).ExecuteAsync();// Global logging behavior will still apply to all steps// Transaction behavior will create one transaction for the entire chainConditional Execution:
varresult=awaitdispatcher.StartWith(newGetUserUseCase(userId)).Then(user =>user.IsActive?newSendNotificationUseCase(user.Id,message):newLogInactiveUserUseCase(user.Id)).ExecuteAsync();Parallel Processing (using multiple chains):
// Execute multiple independent chainsvaruserTask=dispatcher.StartWith(newGetUserUseCase(userId)).Then(user =>newUpdateLastLoginUseCase(user.Id)).ExecuteAsync();varpreferencesTask=dispatcher.StartWith(newGetUserPreferencesUseCase(userId)).Then(prefs =>newApplyThemeUseCase(prefs.ThemeId)).ExecuteAsync();// Wait for both chains to completevaruserResult=awaituserTask;varpreferencesResult=awaitpreferencesTask;Chain Branching:
varresult=awaitdispatcher.StartWith(newProcessOrderUseCase(orderId)).Then(order =>order.IsExpress?dispatcher.StartWith(newExpressShippingUseCase(order)).Then(shipping =>newSendExpressNotificationUseCase(shipping)).ExecuteAsync():dispatcher.StartWith(newStandardShippingUseCase(order)).Then(shipping =>newSendStandardNotificationUseCase(shipping)).ExecuteAsync()).ExecuteAsync();The library provides several extension methods for registering use cases (located in: FunctionalUseCases/Extensions/UseCaseRegistrationExtensions.cs). Registration recap:
// Register use casesservices.AddUseCasesFromAssemblyContaining<MyUseCaseParameter>();// Global execution behaviors (manual, applied to all executions)services.AddScoped(typeof(IExecutionBehavior<,>),typeof(LoggingBehavior<,>));// Per-call behaviors for WithBehavior() (open generics resolved at execution time)services.AddScoped(typeof(TransactionBehavior<,>));services.AddScoped(typeof(ValidationBehavior<,>));services.AddScoped<CachingBehavior<GetUserUseCase,User>>();// Implicit conversion from value to success resultExecutionResult<string>result="Hello World";// Explicit failure creationvarfailure=Execution.Failure<string>("Something went wrong");// Using the + operator (new feature)varresult1=Execution.Success();varresult2=Execution.Failure("Something went wrong");varcombined=result1+result2;// Will be failure with error message// Multiple operationsvarsuccess1=Execution.Success("Value1");varsuccess2=Execution.Success("Value2");varfailure1=Execution.Failure<string>("Error1");varallCombined=success1+success2+failure1;// Will be failure with "Error1"// Using the Combine method directlyvarcombined=Execution.Combine(result1,result2,result3);varresult=awaitdispatcher.ExecuteAsync(useCaseParameter);// Pattern 1: Check success and access valueif(result.ExecutionSucceeded){varvalue=result.GetValueOrThrow();Console.WriteLine(value);}// Pattern 2: Handle failureif(result.ExecutionFailed){varerror=result.Error;Console.WriteLine($"Error: {error?.Message}");// Access additional error informationConsole.WriteLine($"Error Code: {error?.ErrorCode}");Console.WriteLine($"Log Level: {error?.LogLevel}");if(error?.Exception!=null){Console.WriteLine($"Exception: {error.Exception.Message}");}}// Pattern 3: Throw on failureresult.ThrowIfFailed("Custom error message");// Pattern 4: Functional compositionvardisplayName=result.Map(value =>value.ToString()).Bind(value =>string.IsNullOrWhiteSpace(value)?Execution.Failure<string>("Display name is empty","EMPTY_DISPLAY_NAME"):Execution.Success(value)).Match(value =>value, error =>$"Failed: {error.Message}");// ExecutionResult integrates with Microsoft.Extensions.Loggingvarresult=Execution.Failure<string>("Database connection failed",errorCode:"DB_001",logLevel:LogLevel.Critical);// Use logging extension. Preserved exceptions are passed to ILogger.result.Log(logger);Install optional FunctionalUseCases.AspNetCore package to map results without
adding ASP.NET Core dependencies to core package:
usingFunctionalUseCases.AspNetCore;returnresult.ToActionResult();Failures become RFC-style ProblemDetails. Numeric HTTP error codes map
directly; domain codes can provide Properties["statusCode"] or a custom
ExecutionResultHttpOptions.StatusCodeSelector. Exception details remain hidden
unless IncludeExceptionDetails is enabled.
The library includes a comprehensive sample implementation demonstrating the pattern:
- SampleUseCase: Use case parameter containing a name for greeting generation
- SampleUseCaseHandler: Use case implementation that processes the parameter with validation and business logic using ExecutionResult API
Run the sample application to see it in action:
cd Sample
dotnet runUse Case Parameter:
publicclassSampleUseCase:IUseCaseParameter<string>{publicstringName{get;}publicSampleUseCase(stringname){Name=name??thrownewArgumentNullException(nameof(name));}}Use Case Implementation:
publicclassSampleUseCaseHandler:IUseCase<SampleUseCase,string>{publicasyncTask<ExecutionResult<string>>ExecuteAsync(SampleUseCaseuseCaseParameter,CancellationTokencancellationToken=default){if(string.IsNullOrWhiteSpace(useCaseParameter.Name)){returnExecution.Failure<string>("Name cannot be empty or whitespace");}vargreeting=$"Hello, {useCaseParameter.Name}! Welcome to FunctionalUseCases.";returnExecution.Success(greeting);}}Usage:
vardispatcher=serviceProvider.GetRequiredService<IUseCaseDispatcher>();varuseCaseParameter=newSampleUseCase("World");varresult=awaitdispatcher.ExecuteAsync(useCaseParameter);if(result.ExecutionSucceeded)Console.WriteLine(result.CheckedValue);// "Hello, World! Welcome to FunctionalUseCases."elseConsole.WriteLine(result.Error?.Message);FunctionalUseCases/
├── FunctionalUseCases.sln # Solution file
├── FunctionalUseCases/ # Main library
│ ├── ExecutionResult.cs # Result types (generic & non-generic)
│ ├── Execution.cs # Factory methods
│ ├── ExecutionError.cs # Error types
│ ├── ExecutionException.cs # Exception type
│ ├── UseCaseDispatcher.cs # Mediator implementation with execution behavior support
│ ├── PipelineBehaviorDelegate.cs # Execution behavior delegate type
│ ├── Interfaces/ # All interfaces
│ │ ├── IUseCase.cs # Use case parameter and implementation interfaces
│ │ ├── IUseCaseDispatcher.cs # Dispatcher interface
│ │ └── IExecutionBehavior.cs # Execution behavior interface
│ ├── Extensions/ # Extension methods
│ │ ├── ExecutionResultExtensions.cs # Logging & utility extensions
│ │ └── UseCaseRegistrationExtensions.cs # DI extensions (manual behavior registration required)
│ └── Sample/ # Sample implementation
│ ├── SampleUseCase.cs # Example use case parameter
│ ├── SampleUseCaseHandler.cs # Example use case implementation
│ └── LoggingBehavior.cs # Example execution behavior
├── Sample/ # Console application
│ └── Program.cs # Demo application with execution behaviors
└── README.md # This file
# Build the solution
dotnet build
# Run the samplecd Sample && dotnet run
# Run tests (if available)
dotnet testSample Output with Execution Behaviors:
=== FunctionalUseCases Sample Application with Execution Behaviors ===
Example 1: Successful execution
info: Starting execution of use case: SampleUseCase -> String
info: Successfully executed use case: SampleUseCase -> String in 103ms
Success: Hello, World! Welcome to FunctionalUseCases.
Example 2: Failed execution (empty name)
info: Starting execution of use case: SampleUseCase -> String
warn: Use case execution failed: SampleUseCase -> String in 101ms. Error: Name cannot be empty or whitespace
Error: Name cannot be empty or whitespace
Example 3: Use Case Chain
info: Starting execution of use case: SampleUseCase -> String
info: Successfully executed use case: SampleUseCase -> String in 98ms
info: Starting execution of use case: SampleUseCase -> String
info: Successfully executed use case: SampleUseCase -> String in 95ms
Chain Success: Hello, SecondStep-9! Welcome to FunctionalUseCases.
Example 6: Interactive
Enter your name: Alice
info: Starting execution of use case: SampleUseCase -> String
info: Successfully executed use case: SampleUseCase -> String in 92ms
Interactive Success: Hello, Alice! Welcome to FunctionalUseCases.
Examples 4 and 5 demonstrate the WithBehavior() API. Register a per-call behavior such as TransactionBehavior<,> (as shown in the registration section) before running them to see the behavior wrap the execution or the entire chain. If the behavior is not registered, the DI container will throw a missing-service error, highlighting the need to register open generic behaviors explicitly.
- Keep Use Case Parameters Simple: Each use case parameter should represent a single business operation's input data
- Immutable Use Case Parameters: Make use case parameter properties read-only for thread safety
- Validation in Use Cases: Perform validation in use case implementations, not in use case parameters
- Rich Error Handling: Use ExecutionResult with specific error codes and appropriate log levels
- Async Operations: Always use async/await for potentially long-running operations
- Cancellation Support: Support cancellation tokens for responsive applications
- Meaningful Names: Use descriptive names that clearly indicate the business operation being performed
- Single Responsibility: Each use case should handle one specific business scenario
- Global vs Per-Call Behaviors: Use global behaviors for cross-cutting concerns that apply everywhere (logging, monitoring). Use per-call behaviors for context-specific operations (transactions, validation, caching)
- Behavior Registration: Remember to manually register both global and per-call execution behaviors as they are not automatically discovered
- Chain Design: Design use case chains to be atomic units of work - if any step fails, the entire operation should be considered failed
- Result Passing: Structure use case parameters to accept the exact data they need from previous use cases in chains
- Transaction Scope: Use TransactionBehavior on chains rather than individual use cases when you need atomic operations across multiple steps
- Chain-Aware Behaviors: Implement IScopedExecutionBehavior when creating behaviors that need to adapt based on execution context
The library uses clear, intent-revealing interface names:
- IUseCaseParameter: Represents the data/parameters for a use case
- IUseCase: Represents the actual use case implementation/logic
- IExecutionBehavior: Represents cross-cutting behavior that wraps use case execution
- ExecuteAsync: Method name that clearly indicates execution of business logic
This naming convention follows the principle that parameters define what data is needed, while use cases define how that data is processed, and behaviors define how execution is enhanced.
This library uses semantic versioning powered by Nerdbank.GitVersioning:
- Automatic version generation from Git history
- NuGet packages aligned with repository versions
- Runtime version information available via assembly attributes
- Ready for CI/CD pipelines
// Access version information at runtimevarassembly=typeof(Execution).Assembly;varversion=assembly.GetName().Version;varinformationalVersion=assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;// Example output: "1.0.1+136a4d399f" (includes Git commit hash)Console.WriteLine($"Library Version: {informationalVersion}");- .NET 10.0 or later
- Microsoft.Extensions.DependencyInjection (10.0.0)
- Microsoft.Extensions.Logging.Abstractions (10.0.0) - For rich error handling and logging
- Scrutor (5.0.1) - For automatic service registration
- Nerdbank.GitVersioning (3.7.115) - For semantic versioning
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.