Example #1
0
        private static void Main(string[] args)
        {
            var host = new Microsoft.Extensions.Hosting.HostBuilder()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .ConfigureAppConfiguration((context, configuration) =>
            {
                configuration.AddJsonFile("appsettings.json", false, true);

                if (args != null)
                {
                    configuration.AddCommandLine(args);
                }
            })
                       .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                       .ConfigureContainer <ContainerBuilder>((hostContext, builder) =>
            {
            })
                       .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService <IHostedService>();
            })
                       .Build();

            host.Run();
        }
Example #2
0
        //static void Main(string[] args)
        //{
        //    //GlobalConfiguration.Configuration.UseSqlServerStorage("Server=(localdb)\\mssqllocaldb; Database=AcornBox; Trusted_Connection = True; MultipleActiveResultSets = true");
        //    GlobalConfiguration.Configuration.UseSqlServerStorage("Server=acornbox.db; Database=AcornBox; User=sa; Password=Your_password123");

        //    GlobalConfiguration.Configuration.UseActivator(new MyJobActivator());

        //    using (var server = new BackgroundJobServer())
        //    {
        //        Console.WriteLine("Hangfire Server started. Press any key to exit...");
        //        Console.ReadKey();
        //    }
        //}

        static async Task Main(string[] args)
        {
            Console.WriteLine("AcornBox.Worker - Main - Entered");
            var hostBuilder = new Microsoft.Extensions.Hosting.HostBuilder();


            hostBuilder.ConfigureHostConfiguration(configHost =>
            {
                configHost.SetBasePath(Directory.GetCurrentDirectory());
                configHost.AddJsonFile("appsettings.json", optional: true);
                configHost.AddEnvironmentVariables();
                configHost.AddCommandLine(args);
            });

            hostBuilder.ConfigureServices(configServices => {
                configServices.AddHostedService <TimedHostedService>();
            });

            //hostBuilder.ConfigureServices((hostBuilderContext, serviceCollection) =>
            //{


            //    serviceCollection.AddHostedService<TimedHostedService>();
            //});

            await hostBuilder.RunConsoleAsync();

            Console.WriteLine("AcornBox.Worker - Main - Leaving");
        }
Example #3
0
        public void RegisterSingleton()
        {
            var builder = new Microsoft.Extensions.Hosting.HostBuilder()
                          .ConfigureServices((hostingContext, services) =>
            {
                services.AddSingleton <ICalcModule>(AssemblyLoader.LoadDirectory("."));
                // Build an intermediate service provider
                var sp     = services.BuildServiceProvider();
                var module = sp.GetService <ICalcModule>();
                Assert.True(module.Add(2, 3) == 5);
            });

            var b = builder.Build();
            //b.Run();
        }
Example #4
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var host = new Microsoft.Extensions.Hosting.HostBuilder()
                       .ConfigureServices(ConfigureServices)
                       .ConfigureLogging(logging => logging.AddConsole())
                       .UseConsoleLifetime()
                       .Build();

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

                await host.WaitForShutdownAsync();
            }
        }
Example #5
0
        } // End Task RunAsWindowsService

        static async System.Threading.Tasks.Task RunAsDaemon(string[] args)
        {
            Microsoft.Extensions.Hosting.IHost host =
                new Microsoft.Extensions.Hosting.HostBuilder()
                .ConfigureHostConfiguration(configHost =>
            {
                configHost.SetBasePath(System.IO.Directory.GetCurrentDirectory());
                configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                configHost.AddCommandLine(args);
            })
                .ConfigureAppConfiguration((hostContext, configApp) =>
            {
                configApp.SetBasePath(System.IO.Directory.GetCurrentDirectory());
                configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                configApp.AddJsonFile($"appsettings.json", true);
                configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
                configApp.AddCommandLine(args);
            })
                .ConfigureServices((hostContext, services) =>
            {
                services.AddLogging();
                services.AddHostedService <LinuxServiceHost>();
                services.AddSingleton(typeof(ICommonService), typeof(CommonSampleService));

                // My configuration
                services.AddSingleton(new MyConfig());
            })
                .ConfigureLogging((hostContext, configLogging) =>
            {
                // configLogging.AddSerilog(new LoggerConfiguration()
                //           .ReadFrom.Configuration(hostContext.Configuration)
                //           .CreateLogger());
                configLogging.AddConsole();
                configLogging.AddDebug();
            })
                .Build();


            // IServiceCollection isc = host.Services.GetRequiredService<IServiceCollection>();
            // IConfiguration confy = host.Services.GetRequiredService<IConfiguration>();


            // host.Services;

            await host.RunAsync();
        } // End Task RunAsDaemon
        public void can_bootstrap_a_host()
        {
            var input = new NetCoreInput
            {
#if NETCOREAPP2_2
                HostBuilder = new WebHostBuilder()
                              .UseServer(new NulloServer())
                              .UseStartup <EmptyStartup>()
                #else
                HostBuilder = new HostBuilder()
#endif
            };

            using (var host = input.BuildHost())
            {
                host.ShouldNotBeNull();
            }
        }
Example #7
0
        /// <summary>
        /// 生成
        /// </summary>
        /// <typeparam name="TStartup"></typeparam>
        /// <param name="args"></param>
        /// <param name="configureServices"></param>
        /// <returns></returns>
        public IHost Build <TStartup>(string[] args, Action <IServiceCollection, IHostEnvironment> configureServices = null) where TStartup : class, IHostedService
        {
            // 解决乱码问题
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var host = new Microsoft.Extensions.Hosting.HostBuilder()
                       .ConfigureHostConfiguration(configHost =>
            {
                configHost.AddEnvironmentVariables();
                configHost.AddCommandLine(args);
            })
                       .ConfigureServices((hostContext, services) =>
            {
                var envName = hostContext.HostingEnvironment.EnvironmentName;

                services.AddUtils();

                //加载模块
                var modules = services.AddModules(envName);

                //添加对象映射
                services.AddMappers(modules);

                //添加缓存
                services.AddCache(envName);

                //添加数据库
                services.AddDb(envName, modules);

                //自定义服务
                configureServices?.Invoke(services, hostContext.HostingEnvironment);

                //添加主机服务
                services.AddHostedService <TStartup>();

                //添加HttpClient相关
                services.AddHttpClient();
            })
                       .UseLogging()
                       .Build();

            return(host);
        }
Example #8
0
 static async Task Main(string[] args)
 {
     //dotnet GPS.IdentityServer4GrpcServer.dll ASPNETCORE_ENVIRONMENT=Development
     //Environment.SetEnvironmentVariable()
     var builder = new Microsoft.Extensions.Hosting.HostBuilder()
                   .UseEnvironment(args[0].Split('=')[1])
                   .ConfigureAppConfiguration((hostingContext, config) =>
     {
         config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
         config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddJsonFile($"appsettings.{ hostingContext.HostingEnvironment}.json", optional: true, reloadOnChange: true);
         config.AddEnvironmentVariables();
     })
                   .ConfigureLogging((context, logging) =>
     {
         logging.SetMinimumLevel(LogLevel.Debug);
         logging.AddConsole();
     })
                   .ConfigureServices((hostContext, services) =>
     {
         services.AddSingleton <ILoggerFactory, LoggerFactory>();
         services.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
         services.AddSingleton(hostContext.Configuration);
         services.Configure <JwtOptions>(hostContext.Configuration.GetSection("JwtOptions"));
         //services.AddDbContext<GPSIdentityServerDbContext>();
         ServiceProvider build = services.BuildServiceProvider();
         services.AddSingleton <IList <Grpc.Core.Server> >(
             new List <Grpc.Core.Server>()
         {
             new Grpc.Core.Server
             {
                 Services =
                 {
                     IdentityServer4ServiceGrpc.BindService(new IdentityServer4ServiceImpl(build)),
                 },
                 Ports = { new ServerPort("0.0.0.0", 15500, ServerCredentials.Insecure) }
             }
         });
         services.AddSingleton <IHostedService, GrpcBackgroundService>();
     });
     await builder.RunConsoleAsync();
 }
Example #9
0
        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"]);
            }
        }
Example #10
0
        public void ConfigureCustomServiceProvider()
        {
            var hostBuilder = new HostBuilder()
                              .ConfigureServices((hostContext, s) =>
            {
                s.AddTransient <ServiceD>();
                s.AddScoped <ServiceC>();
            })
                              .UseServiceProviderFactory(new FakeServiceProviderFactory())
                              .ConfigureContainer <FakeServiceCollection>((container) =>
            {
                Assert.Null(container.State);
                container.State = "1";
            })
                              .ConfigureContainer <FakeServiceCollection>((container) =>
            {
                Assert.Equal("1", container.State);
                container.State = "2";
            });
            var host         = hostBuilder.Build();
            var fakeServices = host.Services.GetRequiredService <FakeServiceCollection>();

            Assert.Equal("2", fakeServices.State);
        }
Example #11
0
        static async Task Main(string[] args)
        {
            Console.WriteLine(Environment.CurrentDirectory);

            var host = new Microsoft.Extensions.Hosting.HostBuilder()
                       .ConfigureServices((context, services) => {
                services.AddLogging();
                services.AddKadderGrpcServer(builder =>
                {
                    builder.Options = new GrpcServerOptions()
                    {
                        Host          = "0.0.0.0",
                        Port          = 13002,
                        NamespaceName = "Atlantis.Simple",
                        ServiceName   = "AtlantisService",
                        // ScanAssemblies = new string[]
                        // {
                        //     typeof(Program).Assembly.FullName
                        // }
                    };
                    Console.WriteLine(builder.Options.ScanAssemblies[0]);
                    builder.AddInterceptor <LoggerInterceptor>();
                });
                services.AddScoped <IPersonMessageServicer, PersonMessageServicer>();
                services.AddScoped <IAnimalMessageServicer, AnimalMessageServicer>();
                services.AddScoped <INumberMessageServicer, NumberMessageServicer>();
                services.AddScoped <ImplServicer>();
                services.AddScoped <AttributeServicer>();
                services.AddScoped <EndwidthKServicer>();

                Console.WriteLine("Server is running...");
            }).Build();

            host.Services.StartKadderGrpc();
            await host.RunAsync();
        }
Example #12
0
 public void BuildAndDispose()
 {
     using (var host = new HostBuilder()
                       .Build()) { }
 }
Example #13
0
        /// <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>
        ///     <item><description>enables scope validation on the dependency injection container when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development'</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;

                var reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true);

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

                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();
                }
            })
            .UseDefaultServiceProvider((context, options) =>
            {
                var isDevelopment       = context.HostingEnvironment.IsDevelopment();
                options.ValidateScopes  = isDevelopment;
                options.ValidateOnBuild = isDevelopment;
            });

            return(builder);
        }
Example #14
0
        private static void noIHostedServiceAdded()
        {
            IHostBuilder hostBuilder = new Microsoft.Extensions.Hosting.HostBuilder();

            // Vage interface, de implementatie(HostBuilder) roept al die configure stuff aan

            //hostBuilder.ConfigureAppConfiguration((context, builder) =>
            //{
            //    Console.WriteLine("yolo");
            //});

            //hostBuilder.ConfigureHostConfiguration();
            //hostBuilder.ConfigureContainer()
            //hostBuilder.ConfigureServices()

            // Op deze manieer in Build()

            /*
             *     BuildHostConfiguration();
             *     CreateHostingEnvironment();
             *     CreateHostBuilderContext();
             *     BuildAppConfiguration();
             *
             *      // Hier word de hosting environment + Host toegevoegd aan de services              }
             *   CreateServiceProvider();
             * /*
             *
             * public interface IHostingEnvironment
             * {
             *  /// <summary>
             *  /// Gets or sets the name of the application. This property is automatically set by the host to the assembly containing
             *  /// the application entry point.
             *  /// </summary>
             *  string ApplicationName { get; set; }
             *
             *  /// <summary>
             *  /// Gets or sets an <see cref="T:Microsoft.Extensions.FileProviders.IFileProvider" /> pointing at <see cref="P:Microsoft.Extensions.Hosting.IHostingEnvironment.ContentRootPath" />.
             *  /// </summary>
             *  IFileProvider ContentRootFileProvider { get; set; }
             *
             *  /// <summary>
             *  /// Gets or sets the absolute path to the directory that contains the application content files.
             *  /// </summary>
             *  string ContentRootPath { get; set; }
             *
             *  /// <summary>
             *  /// Gets or sets the name of the environment. The host automatically sets this property to the value of the
             *  /// of the "environment" key as specified in configuration.
             *  /// </summary>
             *  string EnvironmentName { get; set; }
             */

            IHost host = hostBuilder.Build();

            //neeueuuhhh. dus die Run() zit niet eens in de IHost
            // Het zit in de HostingAbstractionsHostExtensions (dus)

            /*
             *  public static void Run(this IHost host)
             *  {
             *      host.RunAsync().GetAwaiter().GetResult();
             *  }
             */

            // de default host is dus Microsoft.Extensions.Hosting.Internal.Host
            // je heb 2 Host.cs dus meh die andere is Microsoft.Extenstion.Hosting.Host DUS

            // enfin wat het doet is

            /*
             *  _hostedServices = Services.GetService<IEnumerable<IHostedService>>();
             *
             *  foreach (var hostedService in _hostedServices)
             *  {
             *      // Fire IHostedService.Start
             *      await hostedService.StartAsync(combinedCancellationToken).ConfigureAwait(false);
             *  }
             */

            host.Run();

            // en dat zijn er normaal gesproken op deze manier dus geen (hosted services)
        }