Exemple #1
0
        /// <summary>
        /// Creates a custom HostBuilder for the DebugProxyLauncher so that we can inject
        /// only the needed configurations.
        /// </summary>
        /// <param name="args">Command line arguments passed in</param>
        /// <param name="browserHost">Host where browser is listening for debug connections</param>
        /// <returns><see cref="IHostBuilder" /></returns>
        public static IHostBuilder CreateDefaultBuilder(string[] args, string browserHost)
        {
            var builder = new HostBuilder();

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("blazor-debugproxysettings.json", optional: true, reloadOnChange: true);
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup <Startup>();

                // By default we bind to a dyamic port
                // This can be overridden using an option like "--urls http://localhost:9500"
                webBuilder.UseUrls("http://127.0.0.1:0");
            })
            .ConfigureServices(serviceCollection =>
            {
                serviceCollection.AddSingleton(new DebugProxyOptions
                {
                    BrowserHost = browserHost
                });
            });

            return(builder);
        }
        public TestFixture()
        {
            HostBuilder = new HostBuilder()
                          .ConfigureWebHost(webHost =>
            {
                // Add TestServer
                webHost.UseTestServer();
                webHost.UseStartup <Startup>();
            });

            HostBuilder.ConfigureAppConfiguration(config =>
            {
                var integrationConfig = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json")
                                        .Build();

                config.AddConfiguration(integrationConfig);
            });

            Host = HostBuilder.StartAsync().Result;

            JwtBearerTokenSettings = (IOptions <JwtBearerTokenSettings>)Host.Services.GetService(typeof(IOptions <JwtBearerTokenSettings>));
        }
        public static async Task Main(string[] args)
        {
            var builder = new HostBuilder();

            builder.ConfigureAppConfiguration((hostingContext, configuration) => {
                configuration.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            });

            builder.ConfigureServices((hostingContext, services) => {
                services.AddOptions();
                services.Configure <FileLoggerConfig>(hostingContext.Configuration.GetSection("FileLoggerConfig"));
                services.Configure <RabbitMQConfig>(hostingContext.Configuration.GetSection("RabbitMQ"));
                services.Configure <MongoDBConfig>(hostingContext.Configuration.GetSection("MongoDB"));
                services.Configure <SqlServerDBConfig>(hostingContext.Configuration.GetSection("SqlServer"));
                //services.AddSingleton<ILoggerFactory, FileLoggerFactory>();
                services.AddSingleton <IHostedService, MessagesProcessor>();
            });


            await builder.RunConsoleAsync();
        }
        private static IHost CreateHost()
        {
            var builder = new HostBuilder();

            builder.ConfigureAppConfiguration((context, builder) =>
            {
                builder.Sources.Clear();
                builder
                .SetBasePath(AppContext.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false)
                .AddEnvironmentVariables();
            });

            builder.ConfigureServices((context, builder) =>
            {
                builder.AddLogging(c => c.AddConsole()).Configure <LoggerFilterOptions>(cfg => cfg.MinLevel = LogLevel.Debug);
                builder.AddScoped <Provider>();
                builder.Configure <Settings>(context.Configuration.GetSection("Settings"));
            });


            return(builder.Build());
        }
Exemple #5
0
        public static IHost Build()
        {
            var host = new HostBuilder();

            host.ConfigureAppConfiguration(c =>
            {
                c.AddJsonFile("appsettings.json", optional: true);
                c.AddEnvironmentVariables();

                /*
                 * c.AddSystemsManager(configureSource =>
                 * {
                 *  configureSource.Path = "/parameterstoredemo";
                 *  configureSource.Optional = false;
                 * });
                 */
            });

            host.ConfigureServices((c, s) =>
            {
                s.Configure <AppConfig>(c.Configuration);

                s.AddDefaultAWSOptions(c.Configuration.GetAWSOptions());
                s.AddAWSService <IAmazonDynamoDB>();
                s.AddTransient <IDynamoDBContext, DynamoDBContext>();
                s.AddTransient <IValidator <Create>, CreateValidator>();

                s.AddLogging(x =>
                {
                    x.AddConsole();
                    x.AddAWSProvider();
                    x.SetMinimumLevel(LogLevel.Information);
                });
            });

            return(host.Build());
        }
Exemple #6
0
        static async Task Main(string[] args)
        {
            var builder = new HostBuilder()
                          .ConfigureAppConfiguration(config =>
                                                     config.AddJsonFile("config.json")
                                                     .AddEnvironmentVariables())
                          .ConfigureLogging(log => log.AddConsole())
                          .ConfigureServices(services =>
            {
                services.AddSingleton <IHostedService, QueueProcessorService>();
                services.AddHttpClient <ImportantBackend>()
                .AddTransientHttpErrorPolicy(pb => pb.RetryAsync(5))
                .AddTransientHttpErrorPolicy(pb => pb.CircuitBreaker(5, TimeSpan.FromSeconds(5)));
            });

            var configPath = Environment.GetEnvironmentVariable("ConfigPath");

            if (!string.IsNullOrEmpty(configPath))
            {
                builder.ConfigureAppConfiguration(config => config.AddKeyPerFile(configPath, true));
            }

            await builder.Build().RunAsync();
        }
Exemple #7
0
        static void Main(string[] args)
        {
            var builder = new HostBuilder();

            builder.ConfigureAppConfiguration(b =>
            {
                b.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

                b.Build();
            });

            builder.ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddServiceBus();
                b.AddTimers();
            });

            builder.ConfigureServices((context, services) =>
            {
                services.AddScoped <IPipeFactory <TranslateTextPipeModel>, TranslateTextPipeFactory>();
                services.AddScoped(typeof(IPipeService <>), typeof(QueuePipeService <>));
                services.AddScoped <ITranslateTextService, TranslateTextService>();

                services.AddHostedService <TranslateTextServiceBusListener>();
            });

            var host = builder.Build();

            using (host)
            {
                host.Run();
            }
        }
Exemple #8
0
        /// <summary>
        /// Application enrty point.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        private static Int32 Main(String[] args)
        {
            try {
                var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly();
                Log.Warn($"{assembly.VersionString()} (build: {assembly.BuildString()})");

                // NOTE: .NET Core 3.x CommandLineConfigurationProvider does not support "parameters with no value"
                //       See also: https://github.com/aspnet/Configuration/issues/780
                var isConsoleMode = (Array.IndexOf(args, "--console") >= 0);
                if (isConsoleMode)
                {
                    args = args.Where(a => a != "--console").ToArray();
                }

                //
                // Set-up application Host
                //
                var builder = new HostBuilder()
                              .ConfigureHostConfiguration((config) => config
                                                          .AddEnvironmentVariables("NETCORE_").AddCommandLine(args));

                //
                // Configure application components
                //
                builder
                .ConfigureAppConfiguration((_, config) => config
                                           .SetBasePath(AppDomain.CurrentDomain.BaseDirectory))
                .ConfigureAppConfiguration((hostContext, config) => config
                                           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                           .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true))
                .ConfigureLogging((hostContext, logging) => logging
                                  .AddConfiguration(hostContext.Configuration.GetSection("Logging"))
                                  .ClearProviders().AddNLog())
                .ConfigureServices((hostContext, services) => services
                                   .AddOptions()
                                   .Configure <HostOptions>(hostContext.Configuration.GetSection("Host")))
                .ConfigureDataProviders()
                .ConfigureApiHost()
                .ConfigureServicesHost()
                .ConfigureAppConfiguration((_, config) => config
                                           .AddCommandLine(args));

                //
                // Configure Service vs Console
                //
                if (!isConsoleMode)
                {
                    // IMPORTANT: Update working directory when running as a Windows Service
                    System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

                    builder
                    .ConfigureServices((_, services) => services.AddSingleton <IHostLifetime, Service>());
                }
                else
                {
                    builder
                    // HACK: Supress startup messages written by HostBuilder directly into Console!
                    .ConfigureServices((hostContext, services) => services
                                       // TODO: Find where is this SH*T is read from config by default!
                                       //       See also: https://github.com/aspnet/Extensions/issues/1103
                                       .Configure <ConsoleLifetimeOptions>(hostContext.Configuration.GetSection("Console")))
                    .UseConsoleLifetime();
                }

                //
                // Execute
                //
                builder.Build().Run();

                Log.Warn("Done.");
                Log.Info(String.Empty);
                Log.Info(String.Empty);
                Log.Info(String.Empty);
            } catch (Exception ex) {
                try {
                    Log.Error(ex, ex.Message);
                } catch (Exception) {
                    //
                    // NOTE: Keep console output in place in case someone screw logs configuration
                    //
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine();
                    Console.Error.WriteLine($"FATAL: {ex.DetailedMessage()}");
                    Console.Error.WriteLine();
                    Console.ResetColor();
                }

                return(-1);
            } finally {
                NLog.LogManager.Shutdown();
            }

            return(0);
        }
Exemple #9
0
        static async Task Main(string[] args)
        {
            var builder = new HostBuilder();

            builder.ConfigureHostConfiguration(configuration =>
            {
                configuration.SetBasePath(Directory.GetCurrentDirectory());

                configuration.AddJsonFile("hostsettings.json", true);
                configuration.AddEnvironmentVariables(prefix: "NYBUS_");
                configuration.AddCommandLine(args);
            });

            builder.ConfigureAppConfiguration((context, configuration) =>
            {
                configuration.AddJsonFile("appsettings.json", true);
                configuration.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true);
                configuration.AddEnvironmentVariables(prefix: "NYBUS_");
                configuration.AddCommandLine(args);
            });

            builder.ConfigureServices((context, services) =>
            {
                services.AddHostedService <NybusHostedService>();

                services.AddNybus(nybus =>
                {
                    nybus.UseConfiguration(context.Configuration);

                    nybus.UseRabbitMqBusEngine(rabbitMq =>
                    {
                        rabbitMq.UseConfiguration();

                        rabbitMq.Configure(configuration => configuration.CommandQueueFactory = new StaticQueueFactory("QueueProcessor"));
                    });

                    nybus.SubscribeToCommand <TranslateEducationCommand>();
                });


                services.AddDefaultAWSOptions(context.Configuration.GetAWSOptions("AWS"));
                services.AddAWSService <IAmazonTranslate>();
                services.AddAWSService <IAmazonS3>();

                services.AddHttpClient();
                //services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient());

                services.Configure <TranslateOptions>(context.Configuration.GetSection("Translator"));

                //services.AddCommandHandler<SingleTranslateCommandHandler>();

                services.AddCommandHandler <ImprovedTranslateCommandHandler>();

                services.AddSingleton <IEducationProfileDownloader, HttpClientEducationProfileDownloader>();
                services.AddSingleton <ITextExtractor, HtmlTextExtractor>();
                services.AddSingleton <ITranslator, AmazonTranslateTranslator>();
                services.AddSingleton <ITranslationPersister, AmazonS3TranslationPersister>();

                services.AddHttpClient <IEducationProfileDownloader, HttpClientEducationProfileDownloader>();
            });

            builder.ConfigureLogging((context, logging) =>
            {
                logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                logging.AddAWSProvider(context.Configuration.GetAWSLoggingConfigSection());
                logging.AddConsole();
            });

            var host = builder.Build();

            await host.RunAsync();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            HostBuilder builder = new HostBuilder();

            // Allows us to read the configuration file from current directory
            // (remember to copy those files to the OutputDirectory in VS)
            builder.UseContentRoot(Directory.GetCurrentDirectory());

            builder.ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddServiceBus(); // Support service bus triggers and bindings
            });

            // This step allows the environment variables to be read BEFORE the rest of the configuration
            // This is useful in configuring the hosting environment in debug, by setting the
            // ENVIRONMENT variable in VS
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables();
            });

            // Read the configuration from json file
            builder.ConfigureAppConfiguration((context, config) =>
            {
                IHostingEnvironment env = context.HostingEnvironment;

                config
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                config.AddEnvironmentVariables();
            });

            // Configure logging (you can use the config here, via context.Configuration)
            builder.ConfigureLogging((context, loggingBuilder) =>
            {
                loggingBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();

                // If this key exists in any config, use it to enable App Insights
                var appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                if (!string.IsNullOrEmpty(appInsightsKey))
                {
                    loggingBuilder.AddApplicationInsights(appInsightsKey);
                }
            });

            // Register dependency injected services
            builder.ConfigureServices(services =>
            {
                services.AddTransient <ISimpleService, SimpleService>();
            });

            builder.UseConsoleLifetime();

            IHost host = builder.Build();

            using (host)
            {
                host.Run(); // Start a continuously running WebJob
            }
        }
Exemple #11
0
        /// <summary>
        ///  Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <returns></returns>
        public static IHostBuilder CreateDefaultBuilder()
        {
            var builder = new HostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "ASPNETCORE_");
            });

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();
            })
            .ConfigureLogging((context, logging) =>
            {
                var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
                // the defaults be overridden by the configuration.
                if (isWindows)
                {
                    // Default the EventLogLoggerProvider to warning or above
                    logging.AddFilter <EventLogLoggerProvider>(level => level >= LogLevel.Warning);
                    // Add the EventLogLoggerProvider on windows machines
                    logging.AddEventLog();
                }
            })
            .UseSerilog((context, logger) =>
            {
                ConsoleSwitch.MinimumLevel = context.Configuration.GetValue <LogEventLevel>("Serilog:LevelSwitches:$consoleSwitch");
                FileSwitch.MinimumLevel    = context.Configuration.GetValue <LogEventLevel>("Serilog:LevelSwitches:$fileSwitch");

                logger.ReadFrom.Configuration(context.Configuration)
                .Enrich.FromLogContext()
                .WriteTo.File(
                    "Logs/log-.log",
                    levelSwitch: FileSwitch,
                    rollingInterval: RollingInterval.Day,
                    outputTemplate: "{Timestamp: HH:mm:ss.fff zzz} {SourceContext} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                .WriteTo.Console(
                    levelSwitch: ConsoleSwitch,
                    theme: AnsiConsoleTheme.Code,
                    outputTemplate: "{Timestamp: HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}");
            })
            .UseDefaultServiceProvider((context, options) =>
            {
                var isDevelopment       = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes  = isDevelopment;
                options.ValidateOnBuild = isDevelopment;
            });

            return(builder);
        }
        private static HostBuilder CreateDefaultBuilder(string[] args)
        {
            // Host.CreateDefaultBuilder() is not available before .netcore 3.0.
            // So this is a copied from https://github.com/dotnet/extensions
            var builder = new HostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "DOTNET_");
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                IHostingEnvironment env = hostingContext.HostingEnvironment;
                env.ApplicationName     = Assembly.GetEntryAssembly()?.GetName().Name;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureLogging((hostingContext, logging) =>
            {
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
                // the defaults be overridden by the configuration.
                if (isWindows)
                {
                    // Default the EventLogLoggerProvider to warning or above
                    logging.AddFilter <EventLogLoggerProvider>(level => level >= LogLevel.Warning);
                }

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();

                if (isWindows)
                {
                    // Add the EventLogLoggerProvider on windows machines
                    logging.AddEventLog();
                }
            });

            var options = new ServiceProviderOptions();

            builder.UseServiceProviderFactory(new DefaultServiceProviderFactory(options));

            return(builder);
        }
Exemple #13
0
        internal static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder hostBuilder = new HostBuilder();

            //承载系统自身的配置:
            hostBuilder.ConfigureHostConfiguration(hostConfigurationBuilder =>
            {
                hostConfigurationBuilder.AddJsonFile("commandLineMappings.json", false, false);

                Environment.SetEnvironmentVariable(HostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable(Global.EnvironmentKey));
                hostConfigurationBuilder.AddEnvironmentVariables();
            });

            //应用配置:
            hostBuilder.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
            {
                Global.HostingEnvironment = hostBuilderContext.HostingEnvironment;

                //json文件:
                configurationBuilder.AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{hostBuilderContext.HostingEnvironment.EnvironmentName}.json", true, true)
                .AddJsonFile("exp.json", false, true)
                .AddJsonFile("donateCoinCanContinueStatus.json", false, true);

                //用户机密:
                if (hostBuilderContext.HostingEnvironment.IsDevelopment())
                {
                    //Assembly assembly = Assembly.Load(new AssemblyName(hostBuilderContext.HostingEnvironment.ApplicationName));
                    Assembly assembly = typeof(Program).Assembly;
                    if (assembly != null)
                    {
                        configurationBuilder.AddUserSecrets(assembly, true);
                    }
                }

                //环境变量:
                configurationBuilder.AddExcludeEmptyEnvironmentVariables("Ray_");

                //命令行:
                if (args != null && args.Length > 0)
                {
                    configurationBuilder.AddCommandLine(args, hostBuilderContext.Configuration
                                                        .GetSection("CommandLineMappings")
                                                        .Get <Dictionary <string, string> >());
                }
            });

            //日志:
            hostBuilder.ConfigureLogging((hostBuilderContext, loggingBuilder) =>
            {
                Log.Logger = new LoggerConfiguration()
                             .ReadFrom.Configuration(hostBuilderContext.Configuration)
                             .CreateLogger();
                SelfLog.Enable(x => System.Console.WriteLine(x ?? ""));
            }).UseSerilog();

            //DI容器:
            hostBuilder.ConfigureServices((hostContext, services) =>
            {
                Global.ConfigurationRoot = (IConfigurationRoot)hostContext.Configuration;

                //HostedService:
                services.AddHostedService <BiliBiliToolHostedService>();

                services.AddBiliBiliConfigs(hostContext.Configuration);
                services.AddBiliBiliClientApi(hostContext.Configuration);
                services.AddDomainServices();
                services.AddAppServices();
            });

            return(hostBuilder);
        }
Exemple #14
0
        static async Task Main(string[] args)
        {
            var argsSet = new HashSet <string>(args);

            if (argsSet.Contains(HelpOptions[0]) || argsSet.Contains(HelpOptions[1]))
            {
                ShowHelp();
                return;
            }

            var isService = argsSet.Contains(RunAsServiceOptions[0]) || argsSet.Contains(RunAsServiceOptions[1]);

            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
            var logger = LogManager.LoadConfiguration("NLog.config").GetCurrentClassLogger();

            try
            {
                var builder = new HostBuilder();
                builder.ConfigureAppConfiguration((context, config) =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddYamlFile("config.yml");
                });
                builder.ConfigureServices(services =>
                {
                    services.AddSingleton(
                        new LoggerFactory().AddNLog(new NLogProviderOptions
                    {
                        CaptureMessageTemplates  = true,
                        CaptureMessageProperties = true
                    }));
                    services.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
                    services.AddSingleton(typeof(ILogger), c =>
                    {
                        var factory = c.GetRequiredService <ILoggerFactory>();
                        return(factory.CreateLogger("main"));
                    });
                    services.AddLogging(b =>
                    {
                        b.ClearProviders();
                        b.SetMinimumLevel(LogLevel.Trace);
                    });
                    services.AddSingleton(c =>
                    {
                        var config             = c.GetService <IConfiguration>();
                        var emailConfigSection = config.GetChildren().FirstOrDefault(x => x.Key == "EmailConfiguration");
                        if (emailConfigSection == null)
                        {
                            return(null);
                        }

                        var emailConfiguration = new EmailConfiguration();
                        emailConfigSection.Bind(emailConfiguration);
                        return(emailConfiguration);
                    });
                    services.AddSingleton(c =>
                    {
                        var config = c.GetService <IConfiguration>();
                        var monitoringConfiguration = new MonitoringConfiguration();
                        config.Bind(monitoringConfiguration);
                        return(monitoringConfiguration);
                    });
                    services.AddSingleton <IAlertChannel, EmailAlertChannel>();
                    services.AddSingleton <IAlertNotifier, AlertNotifier>();
                    services.AddHostedService <MonitoringService>();
                });

                if (isService)
                {
                    await builder.RunAsServiceAsync();
                }
                else
                {
                    await builder.RunConsoleAsync();
                }
            }
            catch (AppMonkeyBusinessException e)
            {
                logger.Warn($"{AppName} stopped. {e.Message}");
            }
            catch (Exception e)
            {
                logger.Error(e, $"Critical error occured in {AppName}");
            }
            finally
            {
                LogManager.Shutdown();
            }
        }
Exemple #15
0
        private static HostBuilder BuildHostConfiguration()
        {
            HostBuilder hostBuilder = new HostBuilder();

            hostBuilder.ConfigureAppConfiguration((hostContext, builder) =>
            {
                builder.AddJsonFile("appsettings.json");
                //Add environment specific configuration files.
                var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                if (!string.IsNullOrWhiteSpace(environmentName))
                {
                    builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
                }

                var tempConfig      = builder.Build();
                string kvServiceUri = tempConfig["KeyVaultSettings:ServiceUri"];
                if (!string.IsNullOrWhiteSpace(kvServiceUri))
                {
                    var secretClient = new SecretClient(new Uri(kvServiceUri), new DefaultAzureCredential(
                                                            new DefaultAzureCredentialOptions {
                        ManagedIdentityClientId = tempConfig["ESSManagedIdentity:ClientId"]
                    }));
                    builder.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());
                }

                #if DEBUG
                //Add development overrides configuration
                builder.AddJsonFile("appsettings.local.overrides.json", true, true);
                #endif

                //Add environment variables
                builder.AddEnvironmentVariables();

                Program.ConfigurationBuilder = builder.Build();
            })
            .ConfigureLogging((hostContext, builder) =>
            {
                builder.AddConfiguration(ConfigurationBuilder.GetSection("Logging"));

                 #if DEBUG
                builder.AddSerilog(new LoggerConfiguration()
                                   .WriteTo.File("Logs/UKHO.ExchangeSetService.FulfilmentServiceLogs-.txt", rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}")
                                   .MinimumLevel.Information()
                                   .MinimumLevel.Override("UKHO", LogEventLevel.Debug)
                                   .CreateLogger(), dispose: true);
                 #endif

                builder.AddConsole();

                //Add Application Insights if needed (if key exists in settings)
                string instrumentationKey = ConfigurationBuilder["APPINSIGHTS_INSTRUMENTATIONKEY"];
                if (!string.IsNullOrEmpty(instrumentationKey))
                {
                    builder.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey);
                }

                EventHubLoggingConfiguration eventhubConfig = ConfigurationBuilder.GetSection("EventHubLoggingConfiguration").Get <EventHubLoggingConfiguration>();

                if (!string.IsNullOrWhiteSpace(eventhubConfig.ConnectionString))
                {
                    builder.AddEventHub(config =>
                    {
                        config.Environment            = eventhubConfig.Environment;
                        config.DefaultMinimumLogLevel =
                            (LogLevel)Enum.Parse(typeof(LogLevel), eventhubConfig.MinimumLoggingLevel, true);
                        config.MinimumLogLevels["UKHO"] =
                            (LogLevel)Enum.Parse(typeof(LogLevel), eventhubConfig.UkhoMinimumLoggingLevel, true);
                        config.EventHubConnectionString = eventhubConfig.ConnectionString;
                        config.EventHubEntityPath       = eventhubConfig.EntityPath;
                        config.System   = eventhubConfig.System;
                        config.Service  = eventhubConfig.Service;
                        config.NodeName = eventhubConfig.NodeName;
                        config.AdditionalValuesProvider = additionalValues =>
                        {
                            additionalValues["_AssemblyVersion"] = AssemblyVersion;
                        };
                    });
                }
            })
            .ConfigureServices((hostContext, services) =>
            {
                var buildServiceProvider = services.BuildServiceProvider();

                services.Configure <EssFulfilmentStorageConfiguration>(ConfigurationBuilder.GetSection("EssFulfilmentStorageConfiguration"));
                services.Configure <CacheConfiguration>(ConfigurationBuilder.GetSection("CacheConfiguration"));
                services.Configure <QueuesOptions>(ConfigurationBuilder.GetSection("QueuesOptions"));
                services.Configure <SalesCatalogueConfiguration>(ConfigurationBuilder.GetSection("SalesCatalogue"));

                services.AddScoped <IEssFulfilmentStorageConfiguration, EssFulfilmentStorageConfiguration>();
                services.AddScoped <ISalesCatalogueStorageService, SalesCatalogueStorageService>();
                services.AddScoped <IFulfilmentDataService, FulfilmentDataService>();
                services.AddScoped <IMonitorHelper, MonitorHelper>();
                services.AddScoped <IAzureBlobStorageService, AzureBlobStorageService>();
                services.AddScoped <IAzureBlobStorageClient, AzureBlobStorageClient>();
                services.AddScoped <IAzureMessageQueueHelper, AzureMessageQueueHelper>();
                services.AddScoped <IAzureTableStorageClient, AzureTableStorageClient>();
                services.AddScoped <IFileShareServiceCache, FileShareServiceCache>();


                var retryCount    = Convert.ToInt32(ConfigurationBuilder["RetryConfiguration:RetryCount"]);
                var sleepDuration = Convert.ToDouble(ConfigurationBuilder["RetryConfiguration:SleepDuration"]);
                services.AddHttpClient <IFileShareServiceClient, FileShareServiceClient>(client =>
                {
                    client.BaseAddress     = new Uri(ConfigurationBuilder["FileShareService:BaseUrl"]);
                    var productHeaderValue = new ProductInfoHeaderValue(ExchangeSetServiceUserAgent, AssemblyVersion);
                    client.DefaultRequestHeaders.UserAgent.Add(productHeaderValue);
                    client.Timeout = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationBuilder["FileShareService:TimeOutInMins"]));
                })
                .AddPolicyHandler((services, request) => CommonHelper.GetRetryPolicy(services.GetService <ILogger <IFileShareServiceClient> >(), "File Share", EventIds.RetryHttpClientFSSRequest, retryCount, sleepDuration));

                services.AddHttpClient <ISalesCatalogueClient, SalesCatalogueClient>(client =>
                {
                    client.BaseAddress     = new Uri(ConfigurationBuilder["SalesCatalogue:BaseUrl"]);
                    var productHeaderValue = new ProductInfoHeaderValue(ExchangeSetServiceUserAgent, AssemblyVersion);
                    client.DefaultRequestHeaders.UserAgent.Add(productHeaderValue);
                })
                .AddPolicyHandler((services, request) => CommonHelper.GetRetryPolicy(services.GetService <ILogger <ISalesCatalogueClient> >(), "Sales Catalogue", EventIds.RetryHttpClientSCSRequest, retryCount, sleepDuration));

                services.AddHttpClient <ICallBackClient, CallBackClient>();

                services.AddSingleton <IAuthFssTokenProvider, AuthFssTokenProvider>();
                services.AddSingleton <IAuthScsTokenProvider, AuthScsTokenProvider>();
                services.AddScoped <IFileShareService, FileShareService>();
                services.AddScoped <IFulfilmentFileShareService, FulfilmentFileShareService>();
                services.AddScoped <IFulfilmentAncillaryFiles, FulfilmentAncillaryFiles>();
                services.AddScoped <IFileSystemHelper, FileSystemHelper>();
                services.AddScoped <ISalesCatalogueService, SalesCatalogueService>();
                services.AddScoped <IFulfilmentSalesCatalogueService, FulfilmentSalesCatalogueService>();
                services.AddSingleton <ISmallExchangeSetInstance, SmallExchangeSetInstance>();
                services.AddSingleton <IMediumExchangeSetInstance, MediumExchangeSetInstance>();
                services.AddSingleton <ILargeExchangeSetInstance, LargeExchangeSetInstance>();
                services.AddScoped <IFulfilmentCallBackService, FulfilmentCallBackService>();

                services.Configure <FileShareServiceConfiguration>(ConfigurationBuilder.GetSection("FileShareService"));
                services.Configure <EssManagedIdentityConfiguration>(ConfigurationBuilder.GetSection("ESSManagedIdentity"));
                services.Configure <EssCallBackConfiguration>(ConfigurationBuilder.GetSection("ESSCallBackConfiguration"));

                services.AddDistributedMemoryCache();

                // Add App Insights Telemetry Filter
                var telemetryConfiguration         = buildServiceProvider.GetRequiredService <TelemetryConfiguration>();
                var telemetryProcessorChainBuilder = telemetryConfiguration.TelemetryProcessorChainBuilder;
                telemetryProcessorChainBuilder.Use(next => new AzureDependencyFilterTelemetryProcessor(next));
                telemetryProcessorChainBuilder.Build();
            })
            .ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddAzureStorage();
            });

            return(hostBuilder);
        }
Exemple #16
0
        private static Task Main(string[] args)
        {
            var host = new HostBuilder();

            host.ConfigureAppConfiguration(configureDelegate: (ctx, config) =>
            {
                config.AddJsonFile(path: "settings.json");
                config.AddEnvironmentVariables();
                config.AddCommandLine(args: args);
            });

            host.ConfigureLogging(configureLogging: (_, logging) =>
            {
                logging.AddConsole(configure: options => { options.TimestampFormat = "O"; });
            });

            host.UseConsoleLifetime();

            host.ConfigureServices(configureDelegate: (ctx, services) =>
            {
                services.Configure <MongodbSettings>(config: ctx.Configuration.GetSection(key: "mongodb"));

                services.AddSingleton <IMongodbSettings>(implementationFactory: sp =>
                                                         sp.GetRequiredService <IOptions <MongodbSettings> >().Value);

                services.Configure <RabbitmqSettings>(config: ctx.Configuration.GetSection(key: "rabbitmq"));

                services.AddSingleton <IRabbitmqSettings>(implementationFactory: sp =>
                                                          sp.GetRequiredService <IOptions <RabbitmqSettings> >().Value);

                services.AddSingleton <ISagaRepository <OrderState> >(implementationFactory: sp =>
                {
                    var mongodb = sp.GetRequiredService <IMongodbSettings>();

                    return(new MongoDbSagaRepository <OrderState>(
                               connectionString: mongodb.ConnectionString,
                               database: mongodb.DatabaseName,
                               collectionName: "order-sagas"
                               ));
                });

                services.AddSingleton(implementationFactory: sp =>
                {
                    var repository = sp.GetRequiredService <ISagaRepository <OrderState> >();

                    return(Bus.Factory.CreateUsingRabbitMq(configure: cfg =>
                    {
                        var rabbitmq = sp.GetRequiredService <IRabbitmqSettings>();

                        cfg.Host(
                            hostAddress: new Uri(uriString: rabbitmq.Uri),
                            configure: hc =>
                        {
                            hc.Username(username: rabbitmq.UserName);
                            hc.Password(password: rabbitmq.UserPassword);
                        }
                            );

                        cfg.ReceiveEndpoint(
                            queueName: "order",
                            configureEndpoint: e =>
                            e.StateMachineSaga(stateMachine: new OrderStateMachine(), repository: repository)
                            );
                    }));
                }
                                      );

                services.AddHostedService <MassTransitService>();
            });

            EndpointConvention.Map <LogOrder>(
                destinationAddress: new Uri(uriString: "exchange:contracts:LogOrder"));

            return(host.RunConsoleAsync());
        }
Exemple #17
0
        /// <summary>
        /// See appsettings.json for where to configure various settings required by this console app
        /// (user-secrets in dev, Azure app service Connection Strings and Application Settings in production)
        /// </summary>
        static async Task Main(string[] args)
        {
            var builder = new HostBuilder();

            IConfiguration configuration = null;

            builder.ConfigureHostConfiguration(configHost =>
            {
                configHost.SetBasePath(Directory.GetCurrentDirectory());
                configHost.AddJsonFile("hostsettings.json", optional: true);

                //Need to manually read ASPNETCORE_ENVIRONMENT or else it'll default to Production
                //See: https://github.com/aspnet/AspNetCore/issues/4150
                configHost.AddInMemoryCollection(new[] { new KeyValuePair <string, string>(
                                                             HostDefaults.EnvironmentKey, System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")) });
                configHost.AddEnvironmentVariables();
            });

            builder.ConfigureAppConfiguration((hostContext, configApp) =>
            {
                configApp.SetBasePath(Directory.GetCurrentDirectory());
                configApp.AddJsonFile("appsettings.json", optional: true);
                configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                configApp.AddEnvironmentVariables();

                if (hostContext.HostingEnvironment.EnvironmentName.ToLower() == "development")
                {
                    configApp.AddUserSecrets <Program>();
                }

                configuration = configApp.Build();
            });

            builder.ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddAzureStorage();
            });

            builder.ConfigureLogging((context, b) =>
            {
                b.AddConsole();
            });

            builder.ConfigureServices((context, serviceCollection) =>
            {
                //Need to do this or later when IConfiguration is injected, it'll be missing our user secrets configured for dev above
                serviceCollection.AddSingleton <IConfiguration>(configuration);

                serviceCollection.AddDbContext <NewAlbumsDbContext>(options =>
                                                                    options.UseSqlServer(configuration.GetConnectionString("Default")));

                serviceCollection.GenericServicesSimpleSetup <NewAlbumsDbContext>(
                    new GenericServicesConfig
                {
                    NoErrorOnReadSingleNull = true
                },
                    Assembly.GetAssembly(typeof(BaseAppService))
                    );

                serviceCollection.AddAutoMapper(typeof(IArtistAppService));

                //NewsAlbums.Application services
                serviceCollection.AddTransient <ISpotifyAppService, SpotifyAppService>();
                serviceCollection.AddTransient <IArtistAppService, ArtistAppService>();
                serviceCollection.AddTransient <IAlbumAppService, AlbumAppService>();
                serviceCollection.AddTransient <ISubscriberAppService, SubscriberAppService>();
                serviceCollection.AddTransient <ISubscriptionAppService, SubscriptionAppService>();

                //NewAlbums.Core managers
                serviceCollection.AddTransient <EmailManager>();
                serviceCollection.AddTransient <TemplateManager>();
                serviceCollection.AddTransient <IPathProvider, PathProvider>();

                var serviceProvider = serviceCollection.BuildServiceProvider();

                var loggerFactory = serviceProvider.GetService <ILoggerFactory>();

                string configFileName = "log4net.config";
                if (context.HostingEnvironment.EnvironmentName.ToLower() != "development")
                {
                    configFileName = "log4net.azure.config";
                }

                //Set the retrieved loggerFactory (which is used by ASP.NET logging messages) as the singleton instance to use everywhere
                NewAlbumsLogging.ConfigureLogger(loggerFactory, configFileName);
            });

            //Set the App_Data directory so we can retrieve it later. https://stackoverflow.com/a/48357218
            //string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(Directory.GetCurrentDirectory(), "App_Data"));

            var host = builder.Build();

            using (host)
            {
                await host.StartAsync();

                var jobHost = host.Services.GetService(typeof(IJobHost)) as JobHost;
                await jobHost.CallAsync(typeof(Functions).GetMethod("ProcessNewSpotifyAlbums"));

                await host.StopAsync();
            }
        }
Exemple #18
0
        // Remove overloaded CreateDefaultBuilder method because it's not used

        /// <summary>
        /// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="HostBuilder"/>:
        ///   <list type="bullet">
        ///     <item><description>set the <see cref="IHostEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/></description></item>
        ///     <item><description>load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables</description></item>
        ///     <item><description>load host <see cref="IConfiguration"/> from supplied command line args</description></item>
        ///     <item><description>load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'</description></item>
        ///     <item><description>load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly</description></item>
        ///     <item><description>load app <see cref="IConfiguration"/> from environment variables</description></item>
        ///     <item><description>load app <see cref="IConfiguration"/> from supplied command line args</description></item>
        ///     <item><description>configure the <see cref="ILoggerFactory"/> to log to the console, debug, and event source output</description></item>
        ///   </list>
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
        public static IHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new HostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "DOTNET_");
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
                // the defaults be overridden by the configuration.
                if (isWindows)
                {
                    // Default the EventLogLoggerProvider to warning or above
                    logging.AddFilter <EventLogLoggerProvider>(level => level >= LogLevel.Warning);
                }

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();

                if (isWindows)
                {
                    // Add the EventLogLoggerProvider on windows machines
                    logging.AddEventLog();
                }
            });
            // Remove UseDefaultServiceProvider because method isn't available in .NET Core 2.2

            return(builder);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var host = new HostBuilder();
            // 環境パスのDOTNETCORE_ENVIRONMENTを取得
            var environment = Environment.GetEnvironmentVariable("DOTNETCORE_ENVIRONMENT") ?? "Development";

            // 環境の設定
            host.UseEnvironment(environment);
            // ホストの構成
            host.ConfigureHostConfiguration(config =>
            {
                // Microsoft.Extensions.Configuration
                config.SetBasePath(Directory.GetCurrentDirectory());

                // Microsoft.Extensions.Configuration.EnvironmentVariables
                // 環境変数の先頭文字列"EnvironmentSettingModel_"の変数を取り込む.
                // 取り込んだ環境変数の名前は"EnvironmentSettingModel_"の部分がトリミングされる
                config.AddEnvironmentVariables(prefix: "EnvironmentSettingModel_");

                // Microsoft.Extensions.Configuration.JSON
                config.AddJsonFile($"Settings/setting.json");
                // 環境変数DOTNETCORE_ENVIRONMENTの設定値を使用する。
                config.AddJsonFile($"Settings/setting.{environment}.json");
                config.AddJsonFile($"Settings/loggingSetting.json");

                // Microsoft.Extensions.Configuration.Ini
                config.AddIniFile("Settings/setting.ini");

                // Microsoft.Extensions.Configuration.XML
                config.AddXmlFile("Settings/setting.xml");

                // Microsoft.Extensions.Configuration.Memory
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "InMemoryMessage", "Hello InMemoryCollection!" }
                });

                // Microsoft.Extensions.Configuration.CommandLine
                config.AddCommandLine(args);
            });
            // アプリケーションの構成
            host.ConfigureAppConfiguration((hostContext, config) =>
            {
                var env = hostContext.HostingEnvironment;
                if (env.IsDevelopment())
                {
                    // Microsoft.Extensions.Configuration.UserSecrets
                    config.AddUserSecrets <Program>();
                }
            });
            // サービスの構成
            host.ConfigureServices((hostContext, config) =>
            {
                // Microsoft.Extensions.Configuration
                config.Configure <IniSettingModel>(hostContext.Configuration.GetSection("IniSettingModel"));
                config.Configure <JsonSettingModel>(hostContext.Configuration.GetSection("JsonSettingModel"));
                config.Configure <XmlSettingModel>(hostContext.Configuration.GetSection("XmlSettingModel"));
                config.Configure <UserSecretSettingModel>(hostContext.Configuration.GetSection("UserSecretSettingModel"));
                config.Configure <CommandLineSettingModel>(hostContext.Configuration.GetSection("CommandLineSettingModel"));

                // こういった方法でも使用可能
                var message       = hostContext.Configuration.GetValue <String>("UserSecretSettingModel:Message");
                var messageModel1 = hostContext.Configuration.GetSection("UserSecretSettingModel").Get <BaseSettingModel>();
                var messageModel2 = hostContext.Configuration.GetValue <UserSecretSettingModel>("UserSecretSettingModel");
                var messageModel3 = new BaseSettingModel();
                hostContext.Configuration.GetSection("UserSecretSettingModel").Bind(messageModel3);

                // ConnectionStringだけは別途関数がある
                // var connectionString = hostContext.Configuration.GetConnectionString ("DefaultConnection");

                // Microsoft.Extensions.DependencyInjection
                config.AddHostedService <SampleService>();
                // BackgroundServiceの場合
                // config.AddHostedService<SampleBackgroundService> ();

                // その他サービスのDI
                config.AddTransient <IHoge, LoudHoge>();
            });
            // ロギングの構成
            host.ConfigureLogging((hostContext, config) =>
            {
                // config系の設定を初期化
                config.ClearProviders();
                // appsettings.jsonに記載した設定を反映
                config.AddConfiguration(hostContext.Configuration.GetSection("Logging"));

                // 今回は上記ファイルで指定してるのでコメントアウト.
                // 出力するLogの最低レベルを指定
                // config.SetMinimumLevel (LogLevel.Trace);
                // Microsofot系のLogはInformation以下のレベルは出力しない
                // config.AddFilter ("Microsoft", LogLevel.Information);

                // Microsoft.Extensions.Logging.Console
                config.AddConsole();

                // Microsoft.Extensions.Logging.Debug
                config.AddDebug();

                // Microsoft.Extensions.Logging.EventLog
                config.AddEventLog();

                // Microsoft.Extensions.Logging.EventSource
                // これはEvent Tracing for Windows (ETW)によるLoggin.
                config.AddEventSourceLogger();

                //Microsoft.Extensions.Logging.TraceSource
                Trace.AutoFlush  = true;
                var sourceSwitch = new SourceSwitch("sample")
                {
                    Level = SourceLevels.All
                };
                var listener = new TextWriterTraceListener("Trace.log");
                config.AddTraceSource(sourceSwitch, listener);
            });
            host.UseConsoleLifetime();

            // 起動方法
            // host.RunConsoleAsync();
            // host.Start();
            host.Build().Run();
            // host.Build().Start();
            // host.Build().StartAsync();
        }
Exemple #20
0
        public ConsoleHost(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("System", LogEventLevel.Warning)
                         .MinimumLevel.Override("CoinbasePro", LogEventLevel.Information)
                         .MinimumLevel.Override("Microsoft.Azure.KeyVault", LogEventLevel.Verbose)
                         .MinimumLevel.Override("CoinbasePro.Application.RabbitMq", LogEventLevel.Verbose)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var builder = new HostBuilder().UseConsoleLifetime();

            builder.ConfigureHostConfiguration(config => {
                config.AddEnvironmentVariables(); // pulls environment name from Properties/launchSettings.json
            });

            builder.ConfigureLogging((hostingContext, config) => {
                config.AddSerilog();
            });

            builder.ConfigureAppConfiguration((hostContext, configurationBuilder) =>
            {
                var env = hostContext.HostingEnvironment;
                configurationBuilder.SetBasePath(env.ContentRootPath);

                // These files are copied to bin in the build, so needs rebuild to push changes into app
                configurationBuilder.AddJsonFile("appsettings.json", optional: false, true);
                configurationBuilder.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
                configurationBuilder.AddEnvironmentVariables();

                if (args != null)
                {
                    configurationBuilder.AddCommandLine(args);
                }

                var builtConfig = configurationBuilder.Build();

                Register.AddAzureKeyVault(builtConfig, configurationBuilder);
            });

            builder.ConfigureServices((hostContext, services) =>
            {
                // --------------------------------------------
                // Coinbase Pro log-on credentials, usually these should be saved in the Azure Key vault so they're never exposed
                // without Azure, comment out the azureServiceTokenProvider part above and use the app config file directly
                services.AddSingleton <IAuthenticator>(new Authenticator(hostContext.Configuration["apiKey"]
                                                                         , hostContext.Configuration["apiSecret"]
                                                                         , hostContext.Configuration["passPhrase"]));

                // Customise the HttpClient to ensure we don't ever get HTTP 429 rate limit errors
                services.AddSingleton <IHttpClient>(new RateLimitedHttpClient(3, 2.1));
                services.AddSingleton <ICoinbaseProClient, CoinbaseProClient>();

                // --------------------------------------------
                // The IStartupWorkflow controls the startup order of services in order
                // the ensure inter dependencies receive events or data correctly
                // As all the services are not yet in Github ensure CandleMonitor can still start
                // so use StartupWorkflow.ForCandleMonitorOnly()
                services.AddSingleton(sp => StartupWorkflow.ForCandleMonitorOnly());

                // Usually SQL Server would be used (sql scripts not in Github yet)
                //services.AddSingleton<ICandleProvider, SqlServerCandleProvider>();
                //services.AddTransient<ICandleMonitorFeedProvider, SqlServerCandleMonitorFeed>();

                // Instead use the CSV route for ease of demonstration
                services.AddSingleton <ICandleProvider, CsvCandleProvider>();
                // Setup the markets to pull data for
                services.AddTransient <ICandleMonitorFeedProvider>(sp => new CsvCandleMonitorFeed(new List <CandleMonitorFeeds>()
                {
                    new CandleMonitorFeeds(ProductType.BtcUsd, CandleGranularity.Hour1),
                    new CandleMonitorFeeds(ProductType.EthUsd, CandleGranularity.Hour1),
                    new CandleMonitorFeeds(ProductType.EthEur, CandleGranularity.Minutes15),
                    new CandleMonitorFeeds(ProductType.DaiUsdc, CandleGranularity.Hour1)
                })
                                                                   );

                // Use the event driven candle production / consumption
                services.AddSingleton <CandleProducerConsumer>();
                services.AddSingleton <ICandleProducer>(x => x.GetRequiredService <CandleProducerConsumer>());
                services.AddSingleton <ICandleConsumer>(x => x.GetRequiredService <CandleProducerConsumer>());

                // Add the hosted services
                services.AddSingleton <ICandleMonitor, CandleMonitor>();
                services.AddHostedService <HostedService <ICandleMonitor> >();

                //// Finish up and add database
                //    services.AddDbContext<CryptoDbX>(options =>
                //    {
                //        options.UseSqlServer(hostContext.Configuration.GetConnectionString("MyDbConnection"),
                //            // retry https://blogs.msdn.microsoft.com/cesardelatorre/2017/03/26/using-resilient-entity-framework-core-sql-connections-and-transactions-retries-with-exponential-backoff/
                //            sqlServerOptionsAction: sqlOptions =>
                //            {
                //                sqlOptions.EnableRetryOnFailure(
                //                    maxRetryCount: 5,
                //                    maxRetryDelay: TimeSpan.FromSeconds(30),
                //                    errorNumbersToAdd: null);
                //            });
                //        options.EnableSensitiveDataLogging(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Production");
                //    });

                services.Configure <AppSetting>(hostContext.Configuration);

                // All calls to services.Configure *MUST* have come before this
                ServiceProvider = services.BuildServiceProvider();
            });

            _host = builder.Build();

            //// Automatically perform database migration
            //serviceProvider.GetService<CryptoXContext>().Database.Migrate();
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(Constants.BaseKey, false);

            if (!(key?.GetValue("Configured", 0) is int value) || value == 0)
            {
                return(Host.CreateDefaultBuilder().ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService <UnconfiguredHost>();
                })
                       .UseWindowsService()
                       .ConfigureAccessManagerLogging());
            }

            var host = new HostBuilder();

            host.UseContentRoot(Directory.GetCurrentDirectory());

            string basePath = key?.GetValue("BasePath") as string;

            host.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "DOTNET_");
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            host.UseNLog();

            host.ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.ConfigureAppSettings();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            host.ConfigureAccessManagerLogging();

            host.UseDefaultServiceProvider((context, options) =>
            {
                var isDevelopment       = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes  = isDevelopment;
                options.ValidateOnBuild = isDevelopment;
            });

            host.ConfigureWebHostDefaults(webBuilder =>
            {
                var httpsysConfig = new ConfigurationBuilder().ConfigureAppSettings().Build();

                webBuilder.UseHttpSys(httpsysConfig);
                webBuilder.UseStartup <Startup>();
            });

            host.UseWindowsService();

            return(host);
        }
Exemple #22
0
        static void Main(string[] args)
        {
            var host = new HostBuilder();
            // 環境パスのDOTNETCORE_ENVIRONMENTを取得
            var environment = Environment.GetEnvironmentVariable("DOTNETCORE_ENVIRONMENT") ?? "Development";

            // 環境の設定
            host.UseEnvironment(environment);

            // ホストの構成
            host.ConfigureHostConfiguration(config =>
            {
                // Microsoft.Extensions.Configuration
                config.SetBasePath(Directory.GetCurrentDirectory());

                // Microsoft.Extensions.Configuration.EnvironmentVariables
                // 環境変数の先頭文字列"EnvironmentSettingModel_"の変数を取り込む.
                // 取り込んだ環境変数の名前は"EnvironmentSettingModel_"の部分がトリミングされる
                config.AddEnvironmentVariables(prefix: "EnvironmentSettingModel_");

                // Microsoft.Extensions.Configuration.JSON
                // 環境変数DOTNETCORE_ENVIRONMENTの設定値を使用する。
                config.AddJsonFile($"Settings/setting.json");
                // 同じ定義は後に読み込んだ方で上書きされる
                config.AddJsonFile($"Settings/setting.{environment}.json");

                // Microsoft.Extensions.Configuration.Ini
                config.AddIniFile("Settings/setting.ini");

                // Microsoft.Extensions.Configuration.XML
                config.AddXmlFile("Settings/setting.xml");

                // Microsoft.Extensions.Configuration.Memory
                config.AddInMemoryCollection(new Dictionary <string, string>()
                {
                    { "InMemoryMessage", "Hello InMemoryCollection!" }
                });

                // Microsoft.Extensions.Configuration.CommandLine
                config.AddCommandLine(args);
            });

            // アプリケーションの構成
            host.ConfigureAppConfiguration((hostContext, config) =>
            {
                var env = hostContext.HostingEnvironment;
                if (env.IsDevelopment())
                {
                    // Microsoft.Extensions.Configuration.UserSecrets
                    config.AddUserSecrets <Program>();
                }
            });

            // サービスの構成
            host.ConfigureServices((hostContext, config) =>
            {
                // Microsoft.Extensions.DependencyInjection
                config.AddHostedService <SampleService>();

                // Microsoft.Extensions.Options.ConfigurationExtensions
                config.Configure <IniSettingModel>(hostContext.Configuration.GetSection("IniSettingModel"));
                config.Configure <JsonSettingModel>(hostContext.Configuration.GetSection("JsonSettingModel"));
                config.Configure <XmlSettingModel>(hostContext.Configuration.GetSection("XmlSettingModel"));
                config.Configure <UserSecretModel>(hostContext.Configuration.GetSection("UserSecretSettingModel"));
                config.Configure <CommandLineSettingModel>(hostContext.Configuration.GetSection("CommandLineSettingModel"));

                // こういった方法でも使用可能
                var message       = hostContext.Configuration.GetValue <String>("UserSecretSettingModel:Message");
                var messageModel1 = hostContext.Configuration.GetSection("UserSecretSettingModel").Get <BaseSettingModel>();
                var messageModel2 = hostContext.Configuration.GetValue <UserSecretModel>("UserSecretSettingModel");
                var messageModel3 = new BaseSettingModel();
                hostContext.Configuration.GetSection("UserSecretSettingModel").Bind(messageModel3);
            });

            host.UseConsoleLifetime().Build().Run();
        }
Exemple #23
0
        public static IHost BuildHost(
            DatabaseType databaseType,
            RelationLocatorStrategy strategy,
            IEnumerable <string> configJsonFilenames,
            Action <ContainerBuilder> builderAction = null,
            Action <IClaptrapBootstrapperBuilder> bootstrapperAction = null,
            Action <HostBuilder> configureHostBuilder = null)
        {
            var hostBuilder = new HostBuilder();

            hostBuilder
            .ConfigureAppConfiguration(configurationBuilder =>
            {
                configurationBuilder
                .AddJsonFile("configs/appsettings.json")
                .AddJsonFile($"configs/db_configs/claptrap.{databaseType:G}.json".ToLower())
                .AddJsonFile($"configs/db_configs/claptrap.{databaseType:G}.{strategy:G}.json".ToLower());
                foreach (var filename in configJsonFilenames)
                {
                    configurationBuilder.AddJsonFile(filename);
                }

                configurationBuilder.AddEnvironmentVariables();
            })
            .ConfigureServices(collection =>
            {
                collection.AddLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                    logging.AddNLog();
                });
            })
            .UseServiceProviderFactory(context =>
            {
                return(new AutofacServiceProviderFactory(builder =>
                {
                    var loggerFactory = new ServiceCollection()
                                        .AddLogging(logging =>
                    {
                        logging.SetMinimumLevel(LogLevel.Trace);
                        logging.AddConsole();
                    })
                                        .BuildServiceProvider()
                                        .GetRequiredService <ILoggerFactory>();
                    var claptrapBootstrapperBuilder = new AutofacClaptrapBootstrapperBuilder(loggerFactory)
                                                      .ScanClaptrapModule()
                                                      .AddConfiguration(context.Configuration)
                                                      .ScanClaptrapDesigns(new[]
                    {
                        typeof(IAccount),
                        typeof(Account),
                        typeof(IAccountBalanceMinion),
                        typeof(AccountBalanceMinion),
                        typeof(IAccountHistoryBalanceMinion),
                        typeof(AccountHistoryBalanceMinion)
                    })
                                                      .ConfigureClaptrapDesign(x =>
                                                                               x.ClaptrapOptions.EventCenterOptions.EventCenterType = EventCenterType.None);
                    bootstrapperAction?.Invoke(claptrapBootstrapperBuilder);
                    var claptrapBootstrapper =
                        (AutofacClaptrapBootstrapper)claptrapBootstrapperBuilder
                        .Build();
                    claptrapBootstrapper.Boot(builder);

                    builder.RegisterType <Account>()
                    .AsSelf()
                    .InstancePerDependency();
                    builder.RegisterType <AccountBalanceMinion>()
                    .AsSelf()
                    .InstancePerDependency();

                    builderAction?.Invoke(builder);
                }));
            })
            .ConfigureServices((_, collection) => { collection.AddClaptrapServerOptions(); });
            configureHostBuilder?.Invoke(hostBuilder);
            var host = hostBuilder.Build();

            return(host);
        }
Exemple #24
0
        public static void ConfigureBuilder(HostBuilder builder, string[] args       = null,
                                            Action <SpiderOptions> configureDelegate = null)
        {
            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables("DOTNET_");
                if (args == null)
                {
                    return;
                }

                config.AddCommandLine(args);
            });
            builder.ConfigureAppConfiguration(
                (hostingContext, config) =>
            {
                var hostingEnvironment = hostingContext.HostingEnvironment;
                config.AddJsonFile("appsettings.json", true, true)
                .AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", true, true);
                if (hostingEnvironment.IsDevelopment() && !string.IsNullOrEmpty(hostingEnvironment.ApplicationName))
                {
                    var assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
                    config.AddUserSecrets(assembly, true);
                }

                config.AddEnvironmentVariables();

                var list = new List <string> {
                    "--DOTNET_SPIDER_MODEL", "LOCAL"
                };
                if (args != null)
                {
                    list.AddRange(args);
                }

                config.AddCommandLine(list.ToArray());
            }).ConfigureLogging((hostingContext, logging) =>
            {
                var num = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 1 : 0;
                if (num != 0)
                {
                    logging.AddFilter <EventLogLoggerProvider>(
                        level => level >= LogLevel.Warning);
                }

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
                if (num == 0)
                {
                    return;
                }

                logging.AddEventLog();
            }).ConfigureServices((context, services) =>
            {
                var configuration = context.Configuration;
                if (configuration != null)
                {
                    services.Configure <SpiderOptions>(configuration);
                }

                if (configureDelegate != null)
                {
                    services.Configure(configureDelegate);
                }

                services.AddHttpClient();
                services.AddHostedService <PrintArgumentService>();
                services.AddAgent <HttpClientDownloader>();
                services.TryAddSingleton <IStatisticsClient, StatisticsClient>();
                services.TryAddSingleton <DependenceServices>();
                services.TryAddSingleton <IRequestHasher, RequestHasher>();
                services.TryAddSingleton <IHashAlgorithmService, MurmurHashAlgorithmService>();
            }).UseDefaultServiceProvider((context, options) =>
            {
                var flag = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes  = flag;
                options.ValidateOnBuild = flag;
            });
        }
Exemple #25
0
    public static async Task Main(string[] args)
    {
        var builder = new HostBuilder();

        // allows us to read the configuration file from current directory
        // (remember to copy those files to the OutputDirectory in VS)
        builder.UseContentRoot(Directory.GetCurrentDirectory());

        // configure things like batch size, service bus, etc..
        builder.ConfigureWebJobs(b =>
        {
            b
            .AddAzureStorageCoreServices()
            .AddAzureStorage(options =>
            {
                options.BatchSize       = 1;
                options.MaxDequeueCount = 1;
            })
            ;
        });

        // this step allows the env variable to be read BEFORE the rest of the configuration
        // => this is useful to configure the hosting environment in debug, by setting the
        // ENVIRONMENT variable in VS
        builder.ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();
        });

        // reads the configuration from json file
        builder.ConfigureAppConfiguration((context, config) =>
        {
            var env = context.HostingEnvironment;

            // Adding command line as a configuration source
            config
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

            config.AddEnvironmentVariables();
            if (args != null)
            {
                config.AddCommandLine(args);
            }
        });

        // configure logging (you can use the config here, via context.Configuration)
        builder.ConfigureLogging((context, loggingBuilder) =>
        {
            loggingBuilder.AddConfiguration(context.Configuration.GetSection("Logging"));
            loggingBuilder.AddConsole();

            // If this key exists in any config, use it to enable App Insights
            var appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
            if (!string.IsNullOrEmpty(appInsightsKey))
            {
                loggingBuilder.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
            }
        });

        // inject dependencies via DI
        builder.ConfigureServices((context, services) =>
        {
            services.AddSingleton <INameResolver>(new QueueNameResolver("test"));

            services.AddDbContextPool <DbContext>(options =>
                                                  options.UseSqlServer(context.Configuration.GetConnectionString("DbContext"))
                                                  );
        });

        // finalize host config
        builder.UseConsoleLifetime();

        var host = builder.Build();

        using (host)
        {
            await host.RunAsync();
        }
    }
    private async Task <TestInput> setup(string envName = "Test")
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", envName);
        var hostBuilder = new HostBuilder();
        var host        = await hostBuilder
                          .ConfigureAppConfiguration
                          (
            (hostingContext, config) =>
        {
            config.UseXtiConfiguration(hostingContext.HostingEnvironment, new string[] { });
        }
                          )
                          .ConfigureWebHost(webBuilder =>
        {
            webBuilder
            .UseTestServer()
            .ConfigureServices((context, services) =>
            {
                services.AddSingleton <CurrentAction>();
                services.AddSingleton <TestAuthOptions>();
                services
                .AddAuthentication("Test")
                .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>
                (
                    "Test",
                    options => { }
                );
                services.AddAuthorization(options =>
                {
                    options.DefaultPolicy =
                        new AuthorizationPolicyBuilder("Test")
                        .RequireAuthenticatedUser()
                        .Build();
                });
                services.AddFakesForXtiWebApp(context.Configuration);
                services.AddSingleton <FakeAppContext>();
                services.AddSingleton <ISourceAppContext>(sp => sp.GetRequiredService <FakeAppContext>());
                services.AddSingleton <CachedAppContext>();
                services.AddSingleton <IAppContext>(sp => sp.GetRequiredService <CachedAppContext>());
                services.AddSingleton <FakeUserContext>();
                services.AddSingleton <ISourceUserContext>(sp => sp.GetRequiredService <FakeUserContext>());
                services.AddSingleton <CachedUserContext>();
                services.AddSingleton <IUserContext>(sp => sp.GetRequiredService <CachedUserContext>());
                services.AddSingleton(sp => FakeInfo.AppKey);
                services.AddSingleton <FakeAppOptions>();
                services.AddScoped <FakeAppApiFactory>();
                services.AddScoped <AppApiFactory>(sp => sp.GetRequiredService <FakeAppApiFactory>());
                services.AddSingleton <IAnonClient, FakeAnonClient>();
                services.AddScoped <FakeAppSetup>();
            })
            .Configure(app =>
            {
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseXti();
                app.Run(async(c) =>
                {
                    var currentAction     = c.RequestServices.GetRequiredService <CurrentAction>();
                    currentAction.TempLog = c.RequestServices.GetRequiredService <TempLog>();
                    await currentAction.Action(c);
                });
            });
        })
                          .StartAsync();

        var setup = host.Services.GetRequiredService <FakeAppSetup>();
        await setup.Run(AppVersionKey.Current);

        var userContext = host.Services.GetRequiredService <FakeUserContext>();

        userContext.AddUser(new AppUserName("xartogg"));
        return(new TestInput(host));
    }
Exemple #27
0
        public static async Task Main(string[] args)
        {
            var hostBuilder = new HostBuilder();

            var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            if (environmentName != null)
            {
                hostBuilder.UseEnvironment(environmentName);
            }

            hostBuilder.ConfigureAppConfiguration((hostContext, configApp) =>
            {
                configApp.SetBasePath(Directory.GetCurrentDirectory());
                configApp.AddJsonFile("appsettings.json", optional: true);
                configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                configApp.AddCommandLine(args);
            })
            .ConfigureLogging((hostContext, configLogging) =>
            {
                configLogging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
                configLogging.AddConsole();
                configLogging.AddDebug();
            })
            .ConfigureServices((hostContext, services) =>
            {
                var executorBuilder = services.AddWorkerExecutor(new Uri("https://localhost:44338/"));

                executorBuilder
                .AddTaskType <Tasks.TestTask>();

                executorBuilder
                .MapTaskHandler <Tasks.TestTask, Handlers.TestTaskHandler>();
            })
            .UseConsoleLifetime();

            var host = hostBuilder.Build();

            using (host)
            {
                await host.StartAsync();

                while (true)
                {
                    var v = Console.ReadLine();
                    if (string.IsNullOrEmpty(v))
                    {
                        await host.StopAsync();

                        break;
                    }
                    else
                    {
                        using (var scope = host.Services.CreateScope())
                        {
                            var tasks = scope.ServiceProvider.GetRequiredService <ITaskService>();

                            var taskId = await tasks.PushTaskAsync(new Tasks.TestTask());

                            Console.WriteLine($"Add task {taskId}");
                        }
                    }
                }
            }

            Console.ReadLine();
        }
Exemple #28
0
        /// <summary>
        /// 初始化系统
        /// </summary>
        /// <param name="args"></param>
        public static void Init(string[] args)
        {
            IHostBuilder hostBuilder = new HostBuilder();

            //承载系统自身的配置:
            hostBuilder.ConfigureHostConfiguration(hostConfigurationBuilder =>
            {
                hostConfigurationBuilder.AddJsonFile("commandLineMappings.json", false, false);

                Environment.SetEnvironmentVariable(HostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable(Global.EnvironmentKey));
                hostConfigurationBuilder.AddEnvironmentVariables();
            });

            //应用配置:
            hostBuilder.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
            {
                Global.HostingEnvironment = hostBuilderContext.HostingEnvironment;
                configurationBuilder.AddJsonFile("appsettings.json", false, true)
                .AddJsonFile($"appsettings.{hostBuilderContext.HostingEnvironment.EnvironmentName}.json", true, true)
                .AddJsonFile("exp.json", false, true)
                .AddJsonFile("donateCoinCanContinueStatus.json", false, true);
                if (hostBuilderContext.HostingEnvironment.IsDevelopment())
                {
                    //Assembly assembly = Assembly.Load(new AssemblyName(hostBuilderContext.HostingEnvironment.ApplicationName));
                    Assembly assembly = typeof(Program).Assembly;
                    if (assembly != null)
                    {
                        configurationBuilder.AddUserSecrets(assembly, true);
                    }
                }
                configurationBuilder.AddExcludeEmptyEnvironmentVariables("Ray_");
                if (args != null && args.Length > 0)
                {
                    configurationBuilder.AddCommandLine(args, hostBuilderContext.Configuration
                                                        .GetSection("CommandLineMappings")
                                                        .Get <Dictionary <string, string> >());
                }
            });

            //日志:
            hostBuilder.ConfigureLogging((hostBuilderContext, loggingBuilder) =>
            {
                Log.Logger = new LoggerConfiguration()
                             .ReadFrom.Configuration(hostBuilderContext.Configuration)
                             .CreateLogger();
            }).UseSerilog();

            //DI容器:
            hostBuilder.ConfigureServices((hostContext, services) =>
            {
                Global.ConfigurationRoot = (IConfigurationRoot)hostContext.Configuration;

                services.AddBiliBiliConfigs(hostContext.Configuration);
                services.AddBiliBiliClientApi(hostContext.Configuration);
                services.AddDomainServices();
                services.AddAppServices();
            });

            IHost host = hostBuilder.UseConsoleLifetime().Build();

            Global.ServiceProviderRoot = host.Services;
        }
Exemple #29
0
 public IHostBuilder ConfigureAppConfiguration(Action <HostBuilderContext, IConfigurationBuilder> configureDelegate)
 {
     _hostBuilder.ConfigureAppConfiguration(configureDelegate);
     return(this);
 }
Exemple #30
0
        /// <summary>
        /// Specify the startup type to be used by the host
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static HostBuilder UseStartup <T>(this HostBuilder builder, Func <HostBuilderContext, IEnumerable <FileInfo> > jsonConfigFiles = null) where T : AppStartup
        {
            //config builder
            builder.ConfigureAppConfiguration((h, g) =>
            {
                var files = jsonConfigFiles?.Invoke(h);
                if (files.IsNotNullOrEmpty())
                {
                    foreach (var file in files)
                    {
                        if (file.Exists)
                        {
                            g.AddConfiguration(new ConfigurationBuilder().SetBasePath(h.HostingEnvironment.ContentRootPath).AddJsonFile(file.FullName, true, true).Build());
                        }
                        else
                        {
                            throw new System.IO.FileNotFoundException(string.Format("找不到文件{0}", file.FullName));
                        }
                    }
                }

                builder.Properties["Never.Hosting.Extension.IConfigurationBuilder"] = g;
            });

            //config ioc
            builder.ConfigureServices((h, i) =>
            {
                var ctors = from n in typeof(T).GetConstructors(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                            let parameters = n.GetParameters()
                                             let length = parameters.Length
                                                          select new { ctor = n, parameters = parameters, length = length };

                foreach (var ctor in ctors.OrderByDescending(t => t.length))
                {
                    var paramters = new List <object>(ctor.length);
                    foreach (var p in ctor.parameters)
                    {
                        if (p.ParameterType == typeof(HostBuilderContext))
                        {
                            paramters.Add(h);
                            continue;
                        }
                        if (p.ParameterType == typeof(IServiceCollection))
                        {
                            paramters.Add(i);
                            continue;
                        }
                        if (p.ParameterType == typeof(IHostingEnvironment))
                        {
                            paramters.Add(h.HostingEnvironment);
                            continue;
                        }
                        if (p.ParameterType == typeof(IConfiguration))
                        {
                            paramters.Add(h.Configuration);
                            continue;
                        }
                        if (p.ParameterType == typeof(IConfigurationBuilder))
                        {
                            var config = builder.Properties["Never.Hosting.Extension.IConfigurationBuilder"] as IConfigurationBuilder;
                            builder.Properties.Remove("Never.Hosting.Extension.IConfigurationBuilder");
                            paramters.Add(config);
                            continue;
                        }

                        throw new Exception(string.Format("the parameter type {0} can not resolve in {1} cotrs", p.ParameterType, typeof(T)));
                    }


                    var start = (T)ctor.ctor.Invoke(paramters.ToArray());
                    if (start == null)
                    {
                        return;
                    }

                    var provider = start.ConfigureServices(i);

                    //config serviceprivider
                    builder.UseServiceProviderFactory(new ServiceProviderFactory(provider));
                }
            });

            return(builder);
        }