public HostBuilder Configure(HostBuilder builder) { builder.Match<InstallBuilder>(x => x.Sudo()); builder.Match<UninstallBuilder>(x => x.Sudo()); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.Match<UninstallBuilder>(x => _callback(x)); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.Match<InstallBuilder>(x => x.AddDependency(Name)); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.Match<InstallBuilder>(x => x.RunAs("", "", _accountType)); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.Match<InstallBuilder>(x => x.RunAs(Username, Password, ServiceAccount.User)); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.Match<InstallBuilder>(x => x.SetStartMode(StartMode)); return builder; }
public HostBuilder Configure(HostBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); _settings = builder.Settings; builder.Match<InstallBuilder>(x => x.AfterInstall(ConfigureServiceRecovery)); return builder; }
public static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureHostConfiguration(hostConfig => { hostConfig.SetBasePath(Directory.GetCurrentDirectory()); hostConfig.AddJsonFile("hostsettings.json", optional: false); hostConfig.AddEnvironmentVariables(prefix: "HELTH_"); hostConfig.AddCommandLine(args); }) .ConfigureAppConfiguration((hostConfig, appConfig) => { appConfig.AddJsonFile("appsettings.json", optional: true); appConfig.AddJsonFile($"appsettings.{hostConfig.HostingEnvironment.EnvironmentName}.json", optional: false); }) .ConfigureServices((hostContext, services) => { services.AddTransient <ICronJob, CronJob>(); services.AddDbContext <ApplicationContext>(options => options.UseSqlite(hostContext.Configuration.GetConnectionString("ApplicationContext"))); services.AddHostedService <WorkerService>(); }) .ConfigureLogging((appContext, loggerBuilder) => { loggerBuilder.AddConsole(o => { o.TimestampFormat = "[dd-MM-yyyy HH:mm:ss] "; }); loggerBuilder.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); }
[InlineData(3, "13.113.113.13;34567, 12.112.112.12:23456, 11.111.111.11:12345", "10.0.0.1,11.111.111.11,12.112.112.12", "12.112.112.12", 23456, true)] // Invalid 3rd IP public async Task XForwardedForForwardKnownIps(int limit, string header, string knownIPs, string expectedIp, int expectedPort, bool requireSymmetry) { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor, RequireHeaderSymmetry = requireSymmetry, ForwardLimit = limit, }; foreach (var ip in knownIPs.Split(',').Select(text => IPAddress.Parse(text))) { options.KnownProxies.Add(ip); } app.UseForwardedHeaders(options); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Forwarded-For"] = header; c.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.1"); c.Connection.RemotePort = 99; }); Assert.Equal(expectedIp, context.Connection.RemoteIpAddress.ToString()); Assert.Equal(expectedPort, context.Connection.RemotePort); }
protected virtual IHostBuilder CreateHostBuilder() { var builder = new HostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .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()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); }).ConfigureLogging((hostingContext, logging) => { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LAMBDA_TASK_ROOT"))) { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); } else { logging.AddLambdaLogger(hostingContext.Configuration, "Logging"); } }); return(builder); }
public async Task MultipleAccountTest() { using (IHost host = new HostBuilder() .ConfigureDefaultTestHost <ServiceBusTestJobs>(b => { b.AddServiceBus(); }, nameResolver: _nameResolver) .ConfigureServices(services => { services.AddSingleton <MessagingProvider, CustomMessagingProvider>(); }) .ConfigureServices(s => { s.Configure <HostOptions>(opts => opts.ShutdownTimeout = HostShutdownTimeout); }) .Build()) { await WriteQueueMessage(_secondaryConnectionString, FirstQueueName, "Test"); _topicSubscriptionCalled1 = new ManualResetEvent(initialState: false); _topicSubscriptionCalled2 = new ManualResetEvent(initialState: false); await host.StartAsync(); _topicSubscriptionCalled1.WaitOne(SBTimeoutMills); _topicSubscriptionCalled2.WaitOne(SBTimeoutMills); // ensure all logs have had a chance to flush await Task.Delay(3000); // Wait for the host to terminate await host.StopAsync(); } Assert.Equal("Test-topic-1", _resultMessage1); Assert.Equal("Test-topic-2", _resultMessage2); }
static async Task <int> Main(string[] args) { Console.WriteLine("Console App Example"); var hostBuilder = new HostBuilder() .ConfigureAppConfiguration((hostContext, config) => { if (args != null) { config.AddCommandLine(args); } }) .ConfigureServices((hostContext, services) => { services.AddConsoleCommands(); services.AddSingleton <IHostedService, MyApplication>(); }) .ConfigureLogging((hostContext, logging) => { }); try { await hostBuilder .RunConsoleAsync() .ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return(-1); } return(0); }
static void Main(string[] args) { var builder = new HostBuilder(); builder.UseEnvironment(ConfigurationManager.AppSettings["SPPA:ProvisioningEnvironment"]); builder.ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddServiceBus(sbOptions => { sbOptions.ConnectionString = ConfigurationManager.ConnectionStrings["AzureWebJobsServiceBus"].ConnectionString; sbOptions.MessageHandlerOptions.AutoComplete = true; sbOptions.MessageHandlerOptions.MaxConcurrentCalls = 16; }); }); builder.ConfigureLogging((context, b) => { b.AddConsole(); // If the key exists in settings, use it to enable Application Insights. string instrumentationKey = ConfigurationManager.AppSettings["InstrumentationKey"] ?? context.Configuration["InstrumentationKey"]; if (!string.IsNullOrEmpty(instrumentationKey)) { b.AddApplicationInsightsWebJobs(o => { o.InstrumentationKey = instrumentationKey; }); } }); var host = builder.Build(); using (host) { host.Run(); } }
public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() { // Arrange DiagnosticListener diagnosticListener = null; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { diagnosticListener = app.ApplicationServices.GetRequiredService <DiagnosticListener>(); app.UseDeveloperExceptionPage(); app.Run(context => { throw new Exception("Test exception"); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); // Act await server.CreateClient().GetAsync("/path"); // Assert Assert.NotNull(listener.DiagnosticUnhandledException?.HttpContext); Assert.NotNull(listener.DiagnosticUnhandledException?.Exception); Assert.Null(listener.DiagnosticHandledException?.HttpContext); Assert.Null(listener.DiagnosticHandledException?.Exception); }
public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .ConfigureServices(services => { services.AddCertificateForwarding(options => { }); }) .Configure(app => { app.Use(async(context, next) => { Assert.Null(context.Connection.ClientCertificate); context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; await next(context); }); app.UseCertificateForwarding(); app.Use(async(context, next) => { Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); await next(context); }); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData); }); }
static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { var environment = Environment.GetEnvironmentVariable("ENVIRONMENT"); hostingContext.HostingEnvironment.EnvironmentName = environment; config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); config.AddEnvironmentVariables(); if (hostingContext.HostingEnvironment.IsDevelopment()) { config.AddUserSecrets <Program>(); } }) .ConfigureServices((hostContext, services) => { var configuration = new Configuration(); hostContext.Configuration.Bind(configuration); services.AddOptions <Configuration>(); services.AddDbModule(configuration); //services.AddHostedService<KusamaBlockScannerService>(); services.AddHostedService <UniqueBlockScannerService>(); services.AddHostedService <RegisterNftDepositService>(); services.AddHostedService <RegisterQuoteDepositService>(); services.AddHostedService <TransferSoldNftService>(); services.AddHostedService <LogConfigurationService>(); services.AddSingleton(configuration); services.AddSingleton <IEventBusService, EventBusService>(); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }); await builder.RunConsoleAsync(); }
public static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((host, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); config.AddJsonFile("appsettings.json", true, true); config.AddEnvironmentVariables(); }) .ConfigureServices( (hostcontext, services) => { var envconfig = EnvironmentConfiguration.Bind(hostcontext.Configuration); services.AddSingleton(envconfig); EventFlowOptions.New .Configure(cfg => cfg.IsAsynchronousSubscribersEnabled = true) .UseServiceCollection(services) .AddAspNetCore() .PublishToRabbitMq(RabbitMqConfiguration.With(new Uri($"{envconfig.RabbitMqConnection}"), true, 5, envconfig.RabbitExchange)) .RegisterModule <DomainModule>() // // subscribe services changed // .AddAsynchronousSubscriber <TicketAggregate, TicketId, TicketRegisteredEvent, RabbitMqConsumePersistanceService>() .RegisterServices(s => { s.Register <IHostedService, RabbitConsumePersistenceService>(Lifetime.Singleton); s.Register <IHostedService, RabbitMqConsumePersistanceService>(Lifetime.Singleton); }); }) .ConfigureLogging((hostingContext, logging) => { }); await builder.RunConsoleAsync(); }
public static async Task Main(string[] args) { var host = new HostBuilder() .UseConsoleLifetime() .ConfigureAppConfiguration((hostContext, configApp) => { hostContext.HostingEnvironment.ApplicationName = "Sample Hostbuilder Kafka Consumer Sample"; hostContext.HostingEnvironment.ContentRootPath = Directory.GetCurrentDirectory(); }) .UseKafka(config => // Equivalent to .UseKafka<string, byte[]>() { config.BootstrapServers = new[] { "broker:9092" }; }) .ConfigureServices(container => { // The message that matches the container.AddScoped <IMessageHandler <string, byte[]>, JobMessageHandler>(); // Additional configuration container.Configure <KafkaListenerSettings>(config => { config.Topics = new[] { "topic1" }; config.ConsumerGroup = "group1"; config.AutoOffsetReset = "Latest"; config.AutoCommitIntervall = 5000; config.IsAutocommitEnabled = true; }); }) .ConfigureLogging((ILoggingBuilder loggingBuilder) => { loggingBuilder.AddConsole(); loggingBuilder.AddDebug(); }) .Build(); await host.RunAsync(); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var builder = new HostBuilder(); builder.ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); }); builder.ConfigureLogging((context, b) => { b.AddConsole(); string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]; if (!string.IsNullOrEmpty(instrumentationKey)) { b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey); } }); builder.ConfigureWebJobs(b => { b.AddAzureStorageCoreServices(); b.AddAzureStorage(); }); var host = builder.Build(); using (host) { host.Run(); } }
public async Task Listen_Http3AndSocketsCoexistOnDifferentEndpoints_ClientSuccess(int http3Port, int http1Port) { // Arrange var builder = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(o => { o.Listen(IPAddress.Parse("127.0.0.1"), http3Port, listenOptions => { listenOptions.Protocols = Core.HttpProtocols.Http3; listenOptions.UseHttps(TestResources.GetTestCertificate()); }); o.Listen(IPAddress.Parse("127.0.0.1"), http1Port, listenOptions => { listenOptions.Protocols = Core.HttpProtocols.Http1; listenOptions.UseHttps(TestResources.GetTestCertificate()); }); }) .Configure(app => { app.Run(async context => { await context.Response.WriteAsync("hello, world"); }); }); }) .ConfigureServices(AddTestLogging); using var host = builder.Build(); await host.StartAsync().DefaultTimeout(); await CallHttp3AndHttp1EndpointsAsync(http3Port, http1Port); await host.StopAsync().DefaultTimeout(); }
public static async Task Main(string[] args) { if (args == null) { throw new ArgumentNullException("args"); } string rootPath = Environment.CurrentDirectory; if (args.Length > 0) { rootPath = (string)args[0]; } var host = new HostBuilder() .SetAzureFunctionsEnvironment() .ConfigureLogging(b => { b.SetMinimumLevel(LogLevel.Information); b.AddConsole(); }) .AddScriptHost(o => { o.ScriptPath = rootPath; o.LogPath = Path.Combine(Path.GetTempPath(), "functionshost"); o.IsSelfHost = true; }) .UseConsoleLifetime() .Build(); Console.WriteLine("Starting host"); using (host) { await host.RunAsync(); } }
public async Task Pass_thru_when_context_not_in_services() { var logProvider = new TestLoggerProvider(); using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { app.UseDatabaseErrorPage(); app.UseMiddleware <ContextNotRegisteredInServicesMiddleware>(); #pragma warning disable CS0618 // Type or member is obsolete app.ApplicationServices.GetService <ILoggerFactory>().AddProvider(logProvider); #pragma warning restore CS0618 // Type or member is obsolete }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); try { await server.CreateClient().GetAsync("http://localhost/"); } catch (Exception exception) { Assert.True( exception.GetType().Name == "SqliteException" || exception.InnerException?.GetType().Name == "SqliteException"); } Assert.Contains(logProvider.Logger.Messages.ToList(), m => m.StartsWith(StringsHelpers.GetResourceString("FormatDatabaseErrorPageMiddleware_ContextNotRegistered", typeof(BloggingContext)))); }
static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { // 環境設定ファイルの追加 configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(); configHost.AddCommandLine(args); }) .ConfigureAppConfiguration((hostContext, configApp) => { // アプリケーション設定ファイルの追加 configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(); configApp.AddCommandLine(args); }) .ConfigureServices((hostContext, services) => { // サービスの追加 services.Configure <AppConfigItem>(hostContext.Configuration.GetSection("AppConfig")); services.AddHostedService <BatchService>(); }) .ConfigureLogging((hostContext, configLogging) => { // Application Insight や ロガーの追加 configLogging.AddConsole(); configLogging.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); }
static async Task Main(string[] args) { IHost host = new HostBuilder() .ConfigureAppConfiguration((context, Configuration) => { Configuration.SetBasePath(Directory.GetCurrentDirectory()); Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true); //configApp.AddEnvironmentVariables(prefix: "PREFIX_"); Configuration.AddCommandLine(args); }) .ConfigureLogging(configureLogging => { // configureLogging.AddConsole(); }) .ConfigureServices(services => { // services.AddAuth("Data Source=app.db"); services.AddNLogFactory(); services.AddHostedService <HttpServerHost>(); services.AddHostedService <MqttServerHost>(); }) .Build(); using (var service = host.Services.GetService <ILoggerFactory>()) { logger = service.CreateLogger("host"); } logger?.LogInformation("host is starting..."); // await host.WaitForShutdownAsync(); await host.RunAsync(); // await CreateMultiHostBuilder(args).Build().RunAsync(); }
static void Main(string[] args) { var host = new HostBuilder() .ConfigureLogging(x => { x.AddSerilog(); }) .ConfigureAppConfiguration(x => { if (File.Exists("appsettings.json")) { x.AddJsonFile("appsettings.json"); } x.AddEnvironmentVariables(prefix: "DOTNET_SPIDER_"); }) .ConfigureServices((hostContext, services) => { var configure = new LoggerConfiguration() #if DEBUG .MinimumLevel.Verbose() #else .MinimumLevel.Information() #endif .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console().WriteTo .RollingFile($"/logs/register-center/register-center.log"); Log.Logger = configure.CreateLogger(); services.AddSingleton <SpiderOptions>(); services.AddKafkaEventBus(); services.AddDownloadCenter(x => x.UseMySqlDownloaderAgentStore()); services.AddStatisticsCenter(x => x.UseMySql()); }) .UseEnvironment(args.Contains("/dev") ? EnvironmentName.Development : EnvironmentName.Production) .UseContentRoot(AppDomain.CurrentDomain.BaseDirectory) .Build(); host.Run(); }
public static Task Main(string[] args) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .Build(); var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseConfiguration(config) // Default set of configurations to use, may be subsequently overridden .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) // Override the content root with the current directory .UseUrls("http://*:1000", "https://*:902") .UseEnvironment(Environments.Development) .UseWebRoot("public") .Configure(app => { // Write the application inline, this won't call any startup class in the assembly app.Use(next => context => { return(next(context)); }); }); }) .ConfigureServices(services => { // Configure services that the application can see services.AddSingleton <IMyCustomService, MyCustomService>(); }) .Build(); return(host.RunAsync()); }
public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, string forHeader, string remoteIp, bool loopback, string expected) { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseTestServer() .Configure(app => { var options = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, RequireHeaderSymmetry = true, ForwardLimit = 5, }; if (!loopback) { options.KnownNetworks.Clear(); options.KnownProxies.Clear(); } app.UseForwardedHeaders(options); }); }).Build(); await host.StartAsync(); var server = host.GetTestServer(); var context = await server.SendAsync(c => { c.Request.Headers["X-Forwarded-Proto"] = protoHeader; c.Request.Headers["X-Forwarded-For"] = forHeader; c.Connection.RemoteIpAddress = IPAddress.Parse(remoteIp); }); Assert.Equal(expected, context.Request.Scheme); }
public async Task AddHashiCorpVault_WithWrongMutation_Fails() { // Arrange string secretPath = "secretpath"; string secretKey = "my-value", expected = "s3cr3t"; string userName = _config["Arcus:HashiCorp:UserPass:UserName"]; string password = _config["Arcus:HashiCorp:UserPass:Password"]; var builder = new HostBuilder(); using (HashiCorpVaultTestServer server = await StartServerWithUserPassAsync(userName, password, DefaultDevMountPoint)) { await server.KeyValueV2.WriteSecretAsync( mountPoint : DefaultDevMountPoint, path : secretPath, data : new Dictionary <string, object> { [secretKey] = expected }); var authentication = new UserPassAuthMethodInfo(userName, password); var settings = new VaultClientSettings(server.ListenAddress.ToString(), authentication); // Act builder.ConfigureSecretStore((config, stores) => { stores.AddHashiCorpVault(settings, secretPath, configureOptions: options => options.KeyValueMountPoint = DefaultDevMountPoint, mutateSecretName: secretName => "Test-" + secretName, name: null); }); // Assert IHost host = builder.Build(); var provider = host.Services.GetRequiredService <ISecretProvider>(); await Assert.ThrowsAsync <SecretNotFoundException>(() => provider.GetRawSecretAsync(secretKey)); } }
/// <summary> /// The main entry point for the program. /// </summary> /// <param name="args">The arguments for this program.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile("logsettings.json") .Build(); var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true, reloadOnChange: true); configHost.AddEnvironmentVariables(prefix: "OTS_"); configHost.AddCommandLine(args); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true); configApp.AddEnvironmentVariables(prefix: "OTS_"); configApp.AddCommandLine(args); }) .ConfigureServices(ConfigureServices) .UseSerilog((context, services, loggerConfig) => { var telemetryConfigOptions = services.GetRequiredService <IOptions <TelemetryConfiguration> >(); loggerConfig.ReadFrom.Configuration(configuration) .WriteTo.ApplicationInsights(telemetryConfigOptions.Value, TelemetryConverter.Traces, Serilog.Events.LogEventLevel.Information) .Enrich.FromLogContext(); }) .Build(); // Bind the TCP listener events with handler picking. // This is needed for now because we don't have a separate listening pipeline for generic (non TCP client requests). handlerSelector = host.Services.GetRequiredService <IHandlerSelector>(); clientMap = new Dictionary <IConnection, IClient>();
static void Main(string[] args) { // 支持中文编码 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Log.Logger = new LoggerConfiguration() .WriteTo.Console(LogEventLevel.Debug) .Enrich.FromLogContext() .WriteTo.Async(c => c.File("Logs/logs.log", rollingInterval: RollingInterval.Day)) .CreateLogger(); try { Log.Information("Start ZLMediaKit.Sdk.Demo"); var host = new HostBuilder().ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("application.json", optional: true).Build(); configHost.AddCommandLine(args); }).ConfigureAppConfiguration((context, config) => { }).ConfigureServices((context, services) => { services.ConfigureServices(context.Configuration); }).ConfigureLogging(configureLogging => { }) .UseConsoleLifetime().UseSerilog(Log.Logger).Build(); var close = false; host.RunAsync(); host.WaitForShutdownAsync().ContinueWith(t => close = true); while (!close) { } } catch (Exception) { throw; } Log.Information("Hello World!"); }
public void CanConfigureAppConfigurationAndRetrieveFromDI() { var hostBuilder = new HostBuilder() .ConfigureAppConfiguration((configBuilder) => { configBuilder.AddInMemoryCollection( new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("key1", "value1") }); }) .ConfigureAppConfiguration((configBuilder) => { configBuilder.AddInMemoryCollection( new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("key2", "value2") }); }) .ConfigureAppConfiguration((configBuilder) => { configBuilder.AddInMemoryCollection( new KeyValuePair <string, string>[] { // Hides value2 new KeyValuePair <string, string>("key2", "value3") }); }); using (var host = hostBuilder.Build()) { var config = host.Services.GetService <IConfiguration>(); Assert.NotNull(config); Assert.Equal("value1", config["key1"]); Assert.Equal("value3", config["key2"]); } }
public async Task AddOpenTelemetryInstrumentationCreationAndDisposal() { var testInstrumentation = new TestInstrumentation(); var callbackRun = false; var builder = new HostBuilder().ConfigureServices(services => { services.AddOpenTelemetry(builder => { builder.AddInstrumentation((activitySource) => { callbackRun = true; return(testInstrumentation); }); }); }); var host = builder.Build(); Assert.False(callbackRun); Assert.False(testInstrumentation.Disposed); await host.StartAsync(); Assert.True(callbackRun); Assert.False(testInstrumentation.Disposed); await host.StopAsync(); Assert.True(callbackRun); Assert.False(testInstrumentation.Disposed); host.Dispose(); Assert.True(callbackRun); Assert.True(testInstrumentation.Disposed); }
public static async Task Main(string[] args) { var host = new HostBuilder() // Do this as early as possible, this gives the UI thread time to start .ConfigureWpf() .ConfigureLogging() .ConfigureConfiguration(args) #if (EnableMutex) // Prevent this application from running multiple times .ConfigureSingleInstance(builder => { builder.MutexId = "{application.mutex}"; builder.WhenNotFirstInstance = (hostingEnvironment, logger) => { // This is called when an instance was already started, this is in the second instance logger.LogWarning("Application {0} already running.", hostingEnvironment.ApplicationName); }; }) #endif // Setup CaliburnMicro .ConfigureCaliburnMicro <MainViewModel>() // Provide a view model .ConfigureServices(serviceCollection => { // Make OtherWindow available for DI to MainWindow serviceCollection.AddTransient <OtherViewModel>(); }) #if (EnableMetro) .ConfigureMetro("Light.Orange") #endif .UseConsoleLifetime() // Make sure the application stops when the UI stops .UseWpfLifetime() .Build(); await host.RunAsync(); }
public void UseEnvironment_Development_UserConfigTakesPrecedence() { var hostBuilder = new HostBuilder() .UseEnvironment("Development") .ConfigureDefaultTestHost(b => { b.AddAzureStorage() .AddAzureStorageCoreServices(); }) .ConfigureServices(services => { services.Configure <QueuesOptions>(options => { options.MaxPollingInterval = TimeSpan.FromSeconds(22); }); services.Configure <SingletonOptions>(options => { options.ListenerLockPeriod = TimeSpan.FromSeconds(22); }); }); IHost host = hostBuilder.Build(); var config = host.Services.GetService <DistributedLockManagerContainerProvider>(); var hostingEnvironment = host.Services.GetService <IHostingEnvironment>(); Assert.True(hostingEnvironment.IsDevelopment()); var queuesOptions = host.Services.GetService <IOptions <QueuesOptions> >(); Assert.Equal(TimeSpan.FromSeconds(22), queuesOptions.Value.MaxPollingInterval); var singletonOptions = host.Services.GetService <IOptions <SingletonOptions> >(); Assert.Equal(TimeSpan.FromSeconds(22), singletonOptions.Value.ListenerLockPeriod); }
internal static void Main(string[] args) { IHost host = new HostBuilder() .ConfigureHostConfiguration(builder => builder .AddCommandLine(args)) .ConfigureAppConfiguration((context, builder) => { IHostEnvironment env = context.HostingEnvironment; builder .AddEnvironmentVariables() .AddIniFile("appsettings.ini", optional: true, reloadOnChange: true) .AddIniFile($"appsettings.{env.EnvironmentName}.ini", optional: true, reloadOnChange: true) .AddCommandLine(args); }) .ConfigureLogging((context, builder) => { IHostEnvironment env = context.HostingEnvironment; if (env.IsDevelopment() || env.IsStaging()) { builder.AddDebug(); } Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(context.Configuration) .CreateLogger(); builder.AddSerilog(dispose: true); builder.AddConfiguration(context.Configuration.GetSection("Logging")); }) .ConfigureServices((context, builder) => { builder.AddHostedService <KeepLoggingHostedService>(); }) .UseConsoleLifetime() .Build(); host.Run(); }
public async Task Trigger_IfClassConstructorHasDependencies_CanUseCustomJobActivator() { // Arrange const string expectedResult = "abc"; Mock <IFactory <string> > resultFactoryMock = new Mock <IFactory <string> >(MockBehavior.Strict); resultFactoryMock.Setup(f => f.Create()).Returns(expectedResult); IFactory <string> resultFactory = resultFactoryMock.Object; Mock <IJobActivator> activatorMock = new Mock <IJobActivator>(MockBehavior.Strict); activatorMock.Setup(a => a.CreateInstance <InstanceCustomActivatorProgram>()) .Returns(() => new InstanceCustomActivatorProgram(resultFactory)); IJobActivator activator = activatorMock.Object; CloudQueueMessage message = new CloudQueueMessage("ignore"); var account = new FakeStorageAccount(); await account.AddQueueMessageAsync(message, QueueName); IHost host = new HostBuilder() .ConfigureDefaultTestHost <InstanceCustomActivatorProgram>(builder => { builder.UseStorage(account); }, null, activator) .Build(); // Act var jobHost = host.GetJobHost <InstanceCustomActivatorProgram>(); Assert.NotNull(jobHost); var result = await jobHost.RunTriggerAsync <string>(InstanceCustomActivatorProgram.TaskSource); // Assert Assert.Same(expectedResult, result); }
public static async Task Main(string[] args) { var param = Console.ReadLine(); var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(prefix: "PREFIX_"); configHost.AddCommandLine(args); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(prefix: "PREFIX_"); configApp.AddCommandLine(args); }) .ConfigureServices((hostContext, services) => { services.AddSingleton(new CommandLineArgs { Args = param }); services.AddHostedService <LifetimeEventsHostedService>(); services.AddHostedService <TimedHostedService>(); }) .ConfigureLogging((hostContext, configLogging) => { configLogging.AddConsole(); configLogging.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); }
public HostBuilder Configure(HostBuilder builder) { return new CommandBuilder(builder, _command); }
public HostBuilder Configure(HostBuilder builder) { return new StartBuilder(builder); }
public HostBuilder Configure(HostBuilder builder) { builder.Match<InstallBuilder>(x => x.SetStartMode(_startMode)); return builder; }
public HostBuilder Configure(HostBuilder builder) { builder.Match<InstallBuilder>(x => x.AddDependency(_name)); return builder; }
public HostBuilder Configure(HostBuilder builder) { return builder; }
public HostBuilder Configure(HostBuilder builder) { builder.Match<HelpBuilder>(x => x.SystemHelpTextOnly()); return builder; }
public HostBuilder Configure(HostBuilder builder) { builder.Match<HelpBuilder>(x => x.SetAdditionalHelpText(_text)); return builder; }
public HostBuilder Configure(HostBuilder builder) { builder.Match<InstallBuilder>(x => x.RunAs(_username, _password, _accountType)); return builder; }
public HostBuilder Configure(HostBuilder builder) { builder.Match<InstallBuilder>(x => _callback(x)); return builder; }
public HostBuilder Configure(HostBuilder builder) => builder;