public ApiLauncherFactory() { Port = PortInspector.GetRandomAvailablePorts(1)[0]; var classInfo = new ClassInfo <TStartup>(); var dir = classInfo.ProjectDirectory; var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"; var host = new WebHostBuilder() .UseKestrel() .UseStartup <TStartup>() .UseContentRoot(dir) .UseUrls($"http://localhost:{Port}") .ConfigureAppConfiguration(options => { options.SetBasePath(dir); options.AddJsonFile($"appsettings.{env}.json", true); options.AddEnvironmentVariables(); options.AddCommandLine(new string[] { $"ASPNETCORE_ENVIRONMENT={env}" }); }) .Build(); Task.Run(() => { host.WaitForShutdownAsync(); host.RunAsync(); }); }
/// <summary> /// Constructs a new ProjectPorts instance, populating /// the portPool with a collection of available port numbers /// </summary> /// <param name="config">Configuration object. If /// ApiLauncher:PortPoolSize is present in config, it /// will use that integer value to set the pool size; otherwise, /// it will default to ProjectPorts.DEFAULT_PORT_POOL_SIZE</param> public ProjectPorts(IConfiguration config) { var poolSizeStr = config["ApiLauncher:PortPoolSize"] ?? DEFAULT_PORT_POOL_SIZE.ToString(); var poolSize = int.Parse(poolSizeStr); var ports = PortInspector.GetRandomAvailablePorts(poolSize); foreach (var port in ports) { _portPool.Add(port); } }