Exemplo n.º 1
0
        /// <summary>
        ///     Builds a host for running the given handler.
        /// </summary>
        /// <param name="builder">The builder to use</param>
        /// <param name="runHandler">The run handler</param>
        /// <param name="ct">The cancellation</param>
        /// <returns>Task to be awaited</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static async Task RunAsync(
            this IHostBuilder builder, Func <IServiceProvider, CancellationToken, Task> runHandler,
            CancellationToken ct = default(CancellationToken))
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (runHandler == null)
            {
                throw new ArgumentNullException(nameof(runHandler));
            }

            using (IHostRunContext <HandlerHost> ctx = builder.BuildRunContext <HandlerHost>())
            {
                ILogger <IHostBuilder> logger = ctx.ServiceProvider.GetRequiredService <ILoggerFactory>()
                                                .CreateLogger <IHostBuilder>();
                using (logger.BeginScope("HostType:'{hostTypeName}' ExecutionId:{executionId}", nameof(HandlerHost), ctx.Id))
                {
                    IServiceProvider serviceProvider = ctx.ServiceProvider;
                    ctx.Host.Handler = async c => { await runHandler(serviceProvider, c).ConfigureAwait(false); };
                    await ctx.Host.RunAsync(ct).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 2
0
        public static void Run <THost>(params string[] args) where THost : class, IHost
        {
            using (CancellationTokenSource tokenSource = new CancellationTokenSource())
            {
                void CancelKeyPressHandler(object sender, ConsoleCancelEventArgs cancelEventArgs)
                {
                    // ReSharper disable once AccessToDisposedClosure
                    tokenSource.Cancel();
                    cancelEventArgs.Cancel = true;
                }

                Console.CancelKeyPress += CancelKeyPressHandler;
                try
                {
                    ILoggerFactory loggerFactory = new LoggerFactory()
                                                   .AddSerilog(new LoggerConfiguration()
                                                               .MinimumLevel.Debug()
                                                               .WriteTo.LiterateConsole(LogEventLevel.Debug)
                                                               .CreateLogger());

                    ILogger <DefaultHostRunner> logger = loggerFactory.CreateLogger <DefaultHostRunner>();
                    using (logger.BeginScope("Running"))
                    {
                        using (HostBuilder hostBuilder = new HostBuilder("ASPNETCORE_ENVIRONMENT"))
                        {
                            hostBuilder.SetLoggerFactory(loggerFactory);
                            hostBuilder.AddConfigurationBuilderHandler(param =>
                            {
                                param.Builder
                                .SetBasePath(param.Environment.ContentRootPath)
                                .AddJsonFile("appsettings.json", true, true)
                                .AddJsonFile($"appsettings.{param.Environment.Name}.json", true, true)
                                .AddEnvironmentVariables()
                                .AddCommandLine(args);
                            });
                            hostBuilder.AddConfigurationHandler(param => { });
                            hostBuilder.AddLoggerFactoryHandler(param => { });
                            hostBuilder.AddServiceCollectionHandler(param => { });
                            //hostBuilder.ServiceProviderBuilder = param =>
                            //{
                            //};

                            using (IHostRunContext <THost> ctx = hostBuilder.BuildRunContext <THost>())
                            {
                                ctx.Host.RunAsync(tokenSource.Token).GetAwaiter().GetResult();
                            }
                        }

                        logger.LogInformation("Terminated");
                    }
                }
                finally
                {
                    Console.CancelKeyPress -= CancelKeyPressHandler;
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Builds and runs a host instance of the given type.
        /// </summary>
        /// <typeparam name="THost">The host type</typeparam>
        /// <param name="builder">The builder to use</param>
        /// <param name="ct">The cancellation</param>
        /// <returns>Task to be awaited</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static async Task RunHostAsync <THost>(this IHostBuilder builder,
                                                      CancellationToken ct = default(CancellationToken))
            where THost : class, IHost
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            using (IHostRunContext <THost> ctx = builder.BuildRunContext <THost>())
            {
                ILogger <IHostBuilder> logger = ctx.ServiceProvider.GetRequiredService <ILoggerFactory>()
                                                .CreateLogger <IHostBuilder>();
                using (logger.BeginScope("HostType:'{hostTypeName}' ExecutionId:{executionId}", typeof(THost).Name, ctx.Id))
                {
                    await ctx.Host.RunAsync(ct).ConfigureAwait(false);
                }
            }
        }