Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 4 additions & 1 deletion .claude/settings.local.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
"Bash(for dir in RCommon.*.Tests)",
"Bash(do echo \"=== $dir ===\")",
"Bash(done)",
"Bash(git add:*)"
"Bash(git add:*)",
"Bash(findstr:*)",
"Bash(Select-String -Pattern \"warning CS8\")",
"Bash(Select-String -Pattern \"Build succeeded|Error\\\\\\(s\\\\\\)|Warning\\\\\\(s\\\\\\)|error CS\")"
]
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,6 @@ ASALocalRun/
# BeatPulse healthcheck temp database
healthchecksdb
/Src/RCommon.Persistence.EfCore/IEFCoreConfiguration.cs
/.claude
.claude/settings.local.json
.claude/settings.local.json
157 changes: 157 additions & 0 deletions Src/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
###############################
# Core EditorConfig Options #
###############################

root = true

# All files
[*]
indent_style = space

# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom

###############################
# .NET Coding Conventions #
###############################

###############################
# .NET Coding Conventions #
###############################

[*.{cs,vb}]
# Organize usings
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false

# this. preferences
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_property = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_event = false:silent

# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent

# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent

# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
dotnet_style_readonly_field = true:suggestion

# Expression-level preferences
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent

###############################
# Naming Conventions #
###############################

# Style Definitions
dotnet_naming_style.pascal_case_style.capitalization = pascal_case

# Use PascalCase for constant fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const

###############################
# C# Code Style Rules #
###############################

[*.cs]
# var preferences
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
csharp_style_var_elsewhere = true:silent

# Expression-bodied members
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_accessors = true:silent

# Pattern-matching preferences
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion

# Null-checking preferences
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion

# Modifier preferences
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion

# Expression-level preferences
csharp_prefer_braces = true:silent
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion

###############################
# C# Formatting Rules #
###############################

# New line preferences
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true

# Indentation preferences
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_labels = flush_left

# Space preferences
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_after_comma = true
csharp_space_after_dot = false

# Wrapping preferences
csharp_preserve_single_line_statements = true
csharp_preserve_single_line_blocks = true

##################################
# Visual Basic Code Style Rules #
##################################

[*.vb]
# Modifier preferences
visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion
65 changes: 59 additions & 6 deletions Src/RCommon.ApplicationServices/Commands/CommandBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,33 @@

namespace RCommon.ApplicationServices.Commands
{
/// <summary>
/// Default implementation of <see cref="ICommandBus"/> that dispatches commands to their registered handlers
/// using the dependency injection container.
/// </summary>
/// <remarks>
/// The command bus resolves the appropriate <see cref="ICommandHandler{TResult, TCommand}"/> from the service provider,
/// optionally validates the command via <see cref="IValidationService"/>, and invokes the handler using
/// a dynamically compiled delegate. Compiled handler delegates can optionally be cached for improved performance.
/// </remarks>
public class CommandBus : ICommandBus
{
private readonly ILogger<CommandBus> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly IValidationService _validationService;
private readonly IOptions<CqrsValidationOptions> _validationOptions;
private ICacheService _cacheService;
private ICacheService? _cacheService;
private readonly CachingOptions _cachingOptions;

public CommandBus(ILogger<CommandBus> logger, IServiceProvider serviceProvider, IValidationService validationService,
/// <summary>
/// Initializes a new instance of <see cref="CommandBus"/>.
/// </summary>
/// <param name="logger">Logger for tracing command execution.</param>
/// <param name="serviceProvider">Service provider used to resolve command handlers.</param>
/// <param name="validationService">Service used to validate commands before execution.</param>
/// <param name="validationOptions">Options controlling whether command validation is enabled.</param>
/// <param name="cachingOptions">Options controlling whether dynamically compiled expressions are cached.</param>
public CommandBus(ILogger<CommandBus> logger, IServiceProvider serviceProvider, IValidationService validationService,
IOptions<CqrsValidationOptions> validationOptions, IOptions<CachingOptions> cachingOptions)
{
_logger = logger;
Expand All @@ -58,11 +75,13 @@ public CommandBus(ILogger<CommandBus> logger, IServiceProvider serviceProvider,
_cachingOptions = cachingOptions.Value;
}

/// <inheritdoc />
public async Task<TResult> DispatchCommandAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default)
where TResult : IExecutionResult
{
if (command == null) throw new ArgumentNullException(nameof(command));

// Validate the command if validation is configured for commands
if (_validationOptions.Value != null && _validationOptions.Value.ValidateCommands)
{
// TODO: Would be nice to be able to take validation outcome and put in FailedExecutionResult. Need some casting magic
Expand All @@ -86,15 +105,25 @@ public async Task<TResult> DispatchCommandAsync<TResult>(ICommand<TResult> comma
commandResult?.IsSuccess);
}

return commandResult;
return commandResult!;
}

/// <summary>
/// Resolves and invokes the single registered handler for the given command.
/// </summary>
/// <typeparam name="TResult">The execution result type returned by the handler.</typeparam>
/// <param name="command">The command to execute.</param>
/// <param name="cancellationToken">Token to observe for cancellation.</param>
/// <returns>The result produced by the command handler.</returns>
/// <exception cref="NoCommandHandlersException">Thrown when no handler is registered for the command type.</exception>
/// <exception cref="InvalidOperationException">Thrown when more than one handler is registered for the command type.</exception>
private async Task<TResult> ExecuteHandlerAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken)
where TResult : IExecutionResult
{
var commandType = command.GetType();
var commandExecutionDetails = GetCommandExecutionDetails(commandType);

// Resolve all registered handlers for this command type and enforce exactly one
var commandHandlers = _serviceProvider.GetServices(commandExecutionDetails.CommandHandlerType)
.Cast<ICommandHandler>()
.ToList();
Expand All @@ -114,41 +143,64 @@ private async Task<TResult> ExecuteHandlerAsync<TResult>(ICommand<TResult> comma

var commandHandler = commandHandlers.Single();

// Invoke the handler via the dynamically compiled delegate
var task = (Task<TResult>)commandExecutionDetails.Invoker(commandHandler, command, cancellationToken);
return await task;
}

/// <summary>
/// Holds the resolved handler type and the compiled delegate used to invoke it.
/// </summary>
private class CommandExecutionDetails
{
public Type CommandHandlerType { get; set; }
public Func<ICommandHandler, ICommand, CancellationToken, Task> Invoker { get; set; }
/// <summary>Gets or sets the closed generic handler interface type for the command.</summary>
public Type CommandHandlerType { get; set; } = default!;

/// <summary>Gets or sets the compiled delegate that invokes <c>HandleAsync</c> on the handler.</summary>
public Func<ICommandHandler, ICommand, CancellationToken, Task> Invoker { get; set; } = default!;
}

private const string NameOfExecuteCommand = nameof(
ICommandHandler<
IExecutionResult,
ICommand<IExecutionResult>
>.HandleAsync);

/// <summary>
/// Gets the <see cref="CommandExecutionDetails"/> for the given command type, optionally retrieving
/// from cache if expression caching is enabled.
/// </summary>
/// <param name="commandType">The runtime type of the command being dispatched.</param>
/// <returns>The execution details containing the handler type and compiled invoker delegate.</returns>
private CommandExecutionDetails GetCommandExecutionDetails(Type commandType)
{
// When caching is enabled, cache the compiled expression to avoid repeated reflection/compilation
if (_cachingOptions.CachingEnabled && _cachingOptions.CacheDynamicallyCompiledExpressions)
{
var cachingFactory = _serviceProvider.GetService<ICommonFactory<ExpressionCachingStrategy, ICacheService>>();
Guard.Against<InvalidCacheException>(cachingFactory == null, "We could not properly inject the caching factory: 'ICommonFactory<ExpressionCachingStrategy, ICacheService>>' into the CommandBus");
_cacheService = cachingFactory.Create(ExpressionCachingStrategy.Default);
_cacheService = cachingFactory!.Create(ExpressionCachingStrategy.Default);
return _cacheService.GetOrCreate(CacheKey.With(GetType(), commandType.GetCacheKey()), () => this.BuildCommandDetails(commandType));
}
return this.BuildCommandDetails(commandType);
}

/// <summary>
/// Builds the <see cref="CommandExecutionDetails"/> by reflecting over the command type to determine
/// the handler interface and compiling a delegate for <c>HandleAsync</c>.
/// </summary>
/// <param name="commandType">The runtime type of the command being dispatched.</param>
/// <returns>A new <see cref="CommandExecutionDetails"/> instance.</returns>
private CommandExecutionDetails BuildCommandDetails(Type commandType)
{
// Find the ICommand<TResult> interface to extract the result type
var commandInterfaceType = commandType
.GetTypeInfo()
.GetInterfaces()
.Single(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommand<>));
var commandTypes = commandInterfaceType.GetTypeInfo().GetGenericArguments();

// Construct the closed generic ICommandHandler<TResult, TCommand> type
var commandHandlerType = typeof(ICommandHandler<,>)
.MakeGenericType(commandTypes[0], commandType);

Expand All @@ -157,6 +209,7 @@ private CommandExecutionDetails BuildCommandDetails(Type commandType)
commandType.PrettyPrint(),
commandHandlerType.PrettyPrint());

// Compile a strongly-typed delegate for the handler's HandleAsync method
var invokeExecuteAsync = ReflectionHelper.CompileMethodInvocation<Func<ICommandHandler, ICommand, CancellationToken, Task>>(
commandHandlerType, NameOfExecuteCommand);

Expand Down
16 changes: 15 additions & 1 deletion Src/RCommon.ApplicationServices/Commands/ICommandBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,23 @@

namespace RCommon.ApplicationServices.Commands
{
/// <summary>
/// Defines the contract for a command bus that dispatches commands to their corresponding handlers.
/// </summary>
/// <remarks>
/// Commands represent intent to change state. The bus resolves the appropriate
/// <see cref="ICommandHandler{TResult, TCommand}"/> and returns an <see cref="IExecutionResult"/>.
/// </remarks>
public interface ICommandBus
{
Task<TResult> DispatchCommandAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default)
/// <summary>
/// Dispatches a command to its registered handler and returns the execution result.
/// </summary>
/// <typeparam name="TResult">The type of execution result returned by the handler.</typeparam>
/// <param name="command">The command to dispatch.</param>
/// <param name="cancellationToken">Optional token to cancel the operation.</param>
/// <returns>The execution result produced by the command handler.</returns>
Task<TResult> DispatchCommandAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default)
where TResult : IExecutionResult;
}
}
15 changes: 15 additions & 0 deletions Src/RCommon.ApplicationServices/Commands/ICommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

namespace RCommon.ApplicationServices.Commands
{
/// <summary>
/// Non-generic marker interface for all command handlers. Used for service resolution via reflection.
/// </summary>
public interface ICommandHandler
{
}
Expand All @@ -18,6 +21,12 @@ public interface ICommandHandler
public interface ICommandHandler<in TCommand> : ICommandHandler
where TCommand: ICommand
{
/// <summary>
/// Handles the specified command asynchronously.
/// </summary>
/// <param name="command">The command to handle.</param>
/// <param name="cancellationToken">Token to observe for cancellation.</param>
/// <returns>A task representing the asynchronous operation.</returns>
Task HandleAsync(TCommand command, CancellationToken cancellationToken);
}

Expand All @@ -28,6 +37,12 @@ public interface ICommandHandler<TResult, in TCommand> : ICommandHandler
where TCommand : ICommand<TResult>
where TResult : IExecutionResult
{
/// <summary>
/// Handles the specified command asynchronously and returns an execution result.
/// </summary>
/// <param name="command">The command to handle.</param>
/// <param name="cancellationToken">Token to observe for cancellation.</param>
/// <returns>The execution result produced by handling the command.</returns>
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken);
}
}
Loading