Example #1
0
        /// <inheritdoc/>
        /// <remarks>Commands will be loaded regardless of presence of <see cref="CommandsHandlerAttribute"/>.</remarks>
        /// <exception cref="InvalidOperationException">No mapped initializer for a command was found.</exception>
        public Task <IEnumerable <ICommandInstanceDescriptor> > LoadFromMethodAsync(MethodInfo method, CancellationToken cancellationToken = default)
        {
            List <ICommandInstanceDescriptor> results = new List <ICommandInstanceDescriptor>();

            _log?.LogTrace("Loading command {Name}", method.Name);
            IEnumerable <CommandAttributeBase> attributes = method.GetCustomAttributes <CommandAttributeBase>(true);

            if (!attributes.Any())
            {
                _log?.LogWarning("Cannot initialize command from {Handler}'s method {Name} - {Attribute} missing", method.DeclaringType.FullName, method.Name, nameof(CommandAttributeBase));
                return(NullTask());
            }
            foreach (CommandAttributeBase attribute in attributes)
            {
                // ensure there's a valid initializer
                ICommandInitializer initializer = _initializers.GetInitializer(attribute.GetType());
                if (initializer == null)
                {
                    throw new InvalidOperationException($"No initializer found for command type {attribute.GetType().Name}");
                }

                // add the command
                CommandInstanceDescriptor descriptor = new CommandInstanceDescriptor(attribute, method);
                results.Add(new CommandInstanceDescriptor(attribute, method));
                _log?.LogTrace("Command {Name} from handler {Handler} loaded", descriptor.Method.Name, descriptor.GetHandlerType().Name);
            }
            return(Task.FromResult <IEnumerable <ICommandInstanceDescriptor> >(results));
        }
Example #2
0
 public CommandManager(IVariableHelper variableHelper, [Named("CommandHelper")] IHelper <Action> commandHelper,
                       ICommandRepository commandRepository, ICommandInitializer commandInitializer)
 {
     VariableHelper     = variableHelper;
     CommandHelper      = commandHelper;
     CommandRepository  = (CommandRepository)commandRepository;
     CommandInitializer = (CommandInitializer)commandInitializer;
 }
        /// <summary>
        /// Устанавливает компонент для инициализации экемпляра модели команды.
        /// </summary>
        /// <param name="initializer">Компонента для инициализации модели команды.</param>
        /// <returns>Экземпляр билдера.</returns>
        /// <exception cref="ArgumentNullException">Если <paramref name="initializer"/> равен <c>null</c>.</exception>
        public CommandParserBuilder WithInitializer(ICommandInitializer initializer)
        {
            if (initializer == null)
            {
                throw new ArgumentNullException(nameof(initializer));
            }

            _initializerProvider = () => initializer;
            return(this);
        }
Example #4
0
        public MarsRoverExecuter()
        {
            var programAssembly = Assembly.GetExecutingAssembly();

            var builder = new ContainerBuilder();

            builder.RegisterAssemblyTypes(programAssembly)
            .AsImplementedInterfaces().InstancePerLifetimeScope();
            using (var container = builder.Build())
            {
                commandInitializer = container.Resolve <ICommandInitializer>();
                roverManager       = container.Resolve <IRoverManager>();
            }
        }
        /// <inheritdoc/>
        /// <remarks>Once already started, calling this method again will cause commands to be re-loaded.</remarks>
        public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this._cts.Token))
            {
                await this._lock.WaitAsync(cts.Token).ConfigureAwait(false);

                try
                {
                    this._log?.LogDebug("Initializing commands");

                    // dispose commands since we're reloading them
                    this.DisposeCommands();

                    // ask loader to load from all specified assemblies and types
                    IEnumerable <ICommandInstanceDescriptor> descriptors = await _commandsLoader.LoadFromAssembliesAsync(_options.Assemblies ?? Enumerable.Empty <Assembly>(), cts.Token).ConfigureAwait(false);

                    descriptors = descriptors.Union(await _commandsLoader.LoadFromTypesAsync(_options.Classes.Select(t => t.GetTypeInfo()) ?? Enumerable.Empty <TypeInfo>(), cts.Token).ConfigureAwait(false));

                    // make sure there's no duplicates
                    descriptors = descriptors.Distinct();

                    // for each loaded command, handle pre-initialization and caching
                    foreach (ICommandInstanceDescriptor descriptor in descriptors)
                    {
                        CommandsHandlerAttribute handlerAttribute = descriptor.GetHandlerAttribute();

                        // check if handler is persistent. If so, request it from provider to pre-initialize
                        if (handlerAttribute?.IsPersistent == true)
                        {
                            this._log?.LogDebug("Pre-initializing command handler {Handler}", descriptor.GetHandlerType().Name);
                            this._handlerProvider.GetCommandHandler(descriptor, this._services);
                        }

                        // create all command instances
                        this._log?.LogDebug("Creating command instance {Name} from handler {Handler}", descriptor.Method.Name, descriptor.GetHandlerType().Name);
                        ICommandInitializer initializer = this._initializers.GetInitializer(descriptor.Attribute.GetType());
                        ICommandInstance    instance    = initializer.InitializeCommand(descriptor, _options);
                        this._commands.Add(descriptor, instance);
                    }

                    // mark as started
                    this._started = true;
                    this._log?.LogDebug("{Count} commands loaded", _commands.Count);
                }
                finally
                {
                    this._lock.Release();
                }
            }
        }
Example #6
0
        /// <summary>
        /// Initializes an instance of <see cref="CliApplication"/>.
        /// </summary>
        public CliApplication(ApplicationMetadata metadata, ApplicationConfiguration configuration,
                              IConsole console, ICommandInputParser commandInputParser, ICommandSchemaResolver commandSchemaResolver,
                              ICommandFactory commandFactory, ICommandInitializer commandInitializer, IHelpTextRenderer helpTextRenderer)
        {
            _metadata      = metadata.GuardNotNull(nameof(metadata));
            _configuration = configuration.GuardNotNull(nameof(configuration));

            _console               = console.GuardNotNull(nameof(console));
            _commandInputParser    = commandInputParser.GuardNotNull(nameof(commandInputParser));
            _commandSchemaResolver = commandSchemaResolver.GuardNotNull(nameof(commandSchemaResolver));
            _commandFactory        = commandFactory.GuardNotNull(nameof(commandFactory));
            _commandInitializer    = commandInitializer.GuardNotNull(nameof(commandInitializer));
            _helpTextRenderer      = helpTextRenderer.GuardNotNull(nameof(helpTextRenderer));
        }
Example #7
0
        /// <summary>
        /// Initializes an instance of <see cref="CliApplication"/>.
        /// </summary>
        public CliApplication(ApplicationMetadata metadata, ApplicationConfiguration configuration,
                              IConsole console, ICommandInputParser commandInputParser, ICommandSchemaResolver commandSchemaResolver,
                              ICommandFactory commandFactory, ICommandInitializer commandInitializer, IHelpTextRenderer helpTextRenderer)
        {
            _metadata      = metadata;
            _configuration = configuration;

            _console               = console;
            _commandInputParser    = commandInputParser;
            _commandSchemaResolver = commandSchemaResolver;
            _commandFactory        = commandFactory;
            _commandInitializer    = commandInitializer;
            _helpTextRenderer      = helpTextRenderer;
        }
 public CustomCommandInitializer(Func <ICommandParserSettings> settingsProvider)
 {
     _sourceInitializer = new ParameterAttributeBasedCommandInitializer(settingsProvider);
 }
Example #9
0
 // for initializers provider
 /// <summary>Maps command initializer for a command attribute type in Command Initializer Provider.</summary>
 /// <param name="builder">Hosted Commands Service builder.</param>
 /// <param name="commandArgumentType">Type of command attribute.</param>
 /// <param name="initializer">Initializer to use for given command attribute type.</param>
 /// <seealso cref="ICommandInitializerProvider"/>
 /// <seealso cref="ICommandInitializer"/>
 /// <seealso cref="CommandAttributeBase"/>
 /// <seealso cref="CommandInitializerProviderOptions.Initializers"/>
 public static IHostedCommandsServiceBuilder MapCommandInitializer(this IHostedCommandsServiceBuilder builder, Type commandArgumentType, ICommandInitializer initializer)
 => builder.ConfigureCommandInitializerProvider(options => options.Initializers[commandArgumentType] = initializer);