Exemple #1
0
        private void AddDirectiveMiddlewareAndCommonCommandHandlers()
        {
            AddMiddleware(
                async(originalCommand, context, next) =>
            {
                var commands = PreprocessCommands(originalCommand);

                if (!commands.Contains(originalCommand) && commands.Any())
                {
                    context.CommandToSignalCompletion = commands.Last();
                }

                foreach (var command in commands)
                {
                    if (context.IsComplete)
                    {
                        break;
                    }

                    if (command == originalCommand)
                    {
                        // no new context is needed
                        await next(originalCommand, context);
                    }
                    else
                    {
                        switch (command)
                        {
                        case AnonymousKernelCommand _:
                        case DirectiveCommand _:
                            await command.InvokeAsync(context);
                            break;

                        default:
                            SetHandlingKernel(command, context);
                            var kernel = context.HandlingKernel;
                            if (kernel == this)
                            {
                                var c = KernelInvocationContext.Establish(command);
                                await next(command, c);
                            }
                            else
                            {
                                // forward to appropriate kernel
                                await kernel.SendAsync(command);
                            }
                            break;
                        }
                    }
                }
            });
        }