Rename WebApplication to WebHost

This commit is contained in:
John Luo 2016-01-16 23:11:41 -08:00
parent 0673acedc4
commit cad9ea1df7
29 changed files with 583 additions and 481 deletions

View File

@ -28,16 +28,14 @@ namespace SampleStartups
// Entry point for the application. // Entry point for the application.
public static void Main(string[] args) public static void Main(string[] args)
{ {
var config = WebApplicationConfiguration.GetDefault(args); var host = new WebHostBuilder()
.UseDefaultConfiguration(args)
var application = new WebApplicationBuilder()
.UseConfiguration(config)
.UseStartup<StartupBlockingOnStart>() .UseStartup<StartupBlockingOnStart>()
.Build(); .Build();
using (application) using (host)
{ {
application.Start(); host.Start();
Console.ReadLine(); Console.ReadLine();
} }
} }

View File

@ -27,15 +27,13 @@ namespace SampleStartups
// Entry point for the application. // Entry point for the application.
public static void Main(string[] args) public static void Main(string[] args)
{ {
var config = WebApplicationConfiguration.GetDefault(args); var host = new WebHostBuilder()
.UseDefaultConfiguration(args)
var application = new WebApplicationBuilder()
.UseConfiguration(config)
.UseStartup<StartupConfigureAddresses>() .UseStartup<StartupConfigureAddresses>()
.UseUrls("http://localhost:5000", "http://localhost:5001") .UseUrls("http://localhost:5000", "http://localhost:5001")
.Build(); .Build();
application.Run(); host.Run();
} }
} }
} }

View File

@ -11,7 +11,7 @@ namespace SampleStartups
{ {
public class StartupExternallyControlled public class StartupExternallyControlled
{ {
private IWebApplication _application; private IWebHost _host;
private readonly List<string> _urls = new List<string>(); private readonly List<string> _urls = new List<string>();
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
@ -35,14 +35,14 @@ namespace SampleStartups
public void Start() public void Start()
{ {
_application = new WebApplicationBuilder() _host = new WebHostBuilder()
.UseStartup<StartupExternallyControlled>() .UseStartup<StartupExternallyControlled>()
.Start(_urls.ToArray()); .Start(_urls.ToArray());
} }
public void Stop() public void Stop()
{ {
_application.Dispose(); _host.Dispose();
} }
public void AddUrl(string url) public void AddUrl(string url)

View File

@ -13,7 +13,7 @@ namespace SampleStartups
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
var application = new WebApplicationBuilder() var host = new WebHostBuilder()
.UseServer("Microsoft.AspNet.Server.Kestrel") // Set the server manually .UseServer("Microsoft.AspNet.Server.Kestrel") // Set the server manually
.UseApplicationBasePath(Directory.GetCurrentDirectory()) // Override the application base with the current directory .UseApplicationBasePath(Directory.GetCurrentDirectory()) // Override the application base with the current directory
.UseUrls("http://*:1000", "https://*:902") .UseUrls("http://*:1000", "https://*:902")
@ -35,7 +35,7 @@ namespace SampleStartups
}) })
.Build(); .Build();
application.Run(); host.Run();
} }
} }

View File

@ -27,14 +27,12 @@ namespace SampleStartups
// Entry point for the application. // Entry point for the application.
public static void Main(string[] args) public static void Main(string[] args)
{ {
var config = WebApplicationConfiguration.GetDefault(args); var host = new WebHostBuilder()
.UseDefaultConfiguration(args)
var application = new WebApplicationBuilder()
.UseConfiguration(config)
.UseStartup<StartupHelloWorld>() .UseStartup<StartupHelloWorld>()
.Build(); .Build();
application.Run(); host.Run();
} }
} }
} }

View File

@ -16,7 +16,7 @@ namespace Microsoft.AspNet.Hosting
/// of the "Hosting:Environment" (on Windows) or "Hosting__Environment" (on Linux &amp; OS X) environment variable. /// of the "Hosting:Environment" (on Windows) or "Hosting__Environment" (on Linux &amp; OS X) environment variable.
/// </summary> /// </summary>
// This must be settable! // This must be settable!
string EnvironmentName { get; set; } string EnvironmentName { get; set; }
/// <summary> /// <summary>
/// Gets or sets the absolute path to the directory that contains the web-servable application content files. /// Gets or sets the absolute path to the directory that contains the web-servable application content files.

View File

@ -1,31 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNet.Hosting
{
public interface IWebApplicationBuilder
{
IWebApplication Build();
IDictionary<string, string> Settings { get; }
IWebApplicationBuilder UseConfiguration(IConfiguration configuration);
IWebApplicationBuilder UseServer(IServerFactory factory);
IWebApplicationBuilder UseStartup(Type startupType);
IWebApplicationBuilder ConfigureServices(Action<IServiceCollection> configureServices);
IWebApplicationBuilder Configure(Action<IApplicationBuilder> configureApplication);
IWebApplicationBuilder UseSetting(string key, string value);
}
}

View File

@ -7,9 +7,9 @@ using Microsoft.AspNet.Http.Features;
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
/// <summary> /// <summary>
/// Represents a configured web application /// Represents a configured web host
/// </summary> /// </summary>
public interface IWebApplication : IDisposable public interface IWebHost : IDisposable
{ {
/// <summary> /// <summary>
/// The <see cref="IFeatureCollection"/> exposed by the configured server. /// The <see cref="IFeatureCollection"/> exposed by the configured server.
@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Hosting
IFeatureCollection ServerFeatures { get; } IFeatureCollection ServerFeatures { get; }
/// <summary> /// <summary>
/// The <see cref="IServiceProvider"/> for the application. /// The <see cref="IServiceProvider"/> for the host.
/// </summary> /// </summary>
IServiceProvider Services { get; } IServiceProvider Services { get; }

View File

@ -0,0 +1,73 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNet.Hosting
{
/// <summary>
/// A builder for <see cref="IWebHost"/>
/// </summary>
public interface IWebHostBuilder
{
/// <summary>
/// Builds an <see cref="IWebHost"/> which hosts a web application.
/// </summary>
IWebHost Build();
/// <summary>
/// Gets the raw settings to be used by the web host. Values specified here will override
/// the configuration set by <see cref="UseConfiguration(IConfiguration)"/>.
/// </summary>
IDictionary<string, string> Settings { get; }
/// <summary>
/// Specify the <see cref="IConfiguration"/> to be used by the web host. If no configuration is
/// provided to the builder, the default configuration will be used.
/// </summary>
/// <param name="configuration">The <see cref="IConfiguration"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder UseConfiguration(IConfiguration configuration);
/// <summary>
/// Specify the <see cref="IServerFactory"/> to be used by the web host.
/// </summary>
/// <param name="factory">The <see cref="IServerFactory"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder UseServer(IServerFactory factory);
/// <summary>
/// Specify the startup type to be used by the web host.
/// </summary>
/// <param name="startupType">The <see cref="Type"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder UseStartup(Type startupType);
/// <summary>
/// Specify the delegate that is used to configure the services of the web application.
/// </summary>
/// <param name="configureServices">The delegate that configures the <see cref="IServiceCollection"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices);
/// <summary>
/// Specify the startup method to be used to configure the web application.
/// </summary>
/// <param name="configureApplication">The delegate that configures the <see cref="IApplicationBuilder"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder Configure(Action<IApplicationBuilder> configureApplication);
/// <summary>
/// Add or replace a setting in <see cref="Settings"/>.
/// </summary>
/// <param name="key">The key of the setting to add or replace.</param>
/// <param name="value">The value of the setting to add or replace.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
IWebHostBuilder UseSetting(string key, string value);
}
}

View File

@ -3,7 +3,7 @@
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
public static class WebApplicationDefaults public static class WebHostDefaults
{ {
public static readonly string ApplicationKey = "application"; public static readonly string ApplicationKey = "application";
public static readonly string DetailedErrorsKey = "detailedErrors"; public static readonly string DetailedErrorsKey = "detailedErrors";

View File

@ -1,7 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ServiceProcess; using System.ServiceProcess;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -10,25 +9,25 @@ namespace Microsoft.AspNet.Hosting.WindowsServices
/// <summary> /// <summary>
/// Provides an implementation of a Windows service that hosts ASP.NET. /// Provides an implementation of a Windows service that hosts ASP.NET.
/// </summary> /// </summary>
public class WebApplicationService : ServiceBase public class WebHostService : ServiceBase
{ {
private IWebApplication _application; private IWebHost _host;
private bool _stopRequestedByWindows; private bool _stopRequestedByWindows;
/// <summary> /// <summary>
/// Creates an instance of <c>WebApplicationService</c> which hosts the specified web application. /// Creates an instance of <c>WebHostService</c> which hosts the specified web application.
/// </summary> /// </summary>
/// <param name="application">The web application to host in the Windows service.</param> /// <param name="host">The configured web host containing the web application to host in the Windows service.</param>
public WebApplicationService(IWebApplication application) public WebHostService(IWebHost host)
{ {
_application = application; _host = host;
} }
protected sealed override void OnStart(string[] args) protected sealed override void OnStart(string[] args)
{ {
OnStarting(args); OnStarting(args);
_application _host
.Services .Services
.GetRequiredService<IApplicationLifetime>() .GetRequiredService<IApplicationLifetime>()
.ApplicationStopped .ApplicationStopped
@ -40,7 +39,7 @@ namespace Microsoft.AspNet.Hosting.WindowsServices
} }
}); });
_application.Start(); _host.Start();
OnStarted(); OnStarted();
} }
@ -49,7 +48,7 @@ namespace Microsoft.AspNet.Hosting.WindowsServices
{ {
_stopRequestedByWindows = true; _stopRequestedByWindows = true;
OnStopping(); OnStopping();
_application?.Dispose(); _host?.Dispose();
OnStopped(); OnStopped();
} }

View File

@ -6,37 +6,37 @@ using System.ServiceProcess;
namespace Microsoft.AspNet.Hosting.WindowsServices namespace Microsoft.AspNet.Hosting.WindowsServices
{ {
/// <summary> /// <summary>
/// Extensions to <see cref="IWebApplication" for hosting inside a Windows service. /> /// Extensions to <see cref="IWebHost" for hosting inside a Windows service. />
/// </summary> /// </summary>
public static class WebApplicationExtensions public static class WebHostWindowsServiceExtensions
{ {
/// <summary> /// <summary>
/// Runs the specified web application inside a Windows service and blocks until the service is stopped. /// Runs the specified web application inside a Windows service and blocks until the service is stopped.
/// </summary> /// </summary>
/// <param name="application">An instance of the <see cref="IWebApplication"/> to host in the Windows service.</param> /// <param name="host">An instance of the <see cref="IWebHost"/> to host in the Windows service.</param>
/// <example> /// <example>
/// This example shows how to use <see cref="WebApplicationService.Run"/>. /// This example shows how to use <see cref="WebHostService.Run"/>.
/// <code> /// <code>
/// public class Program /// public class Program
/// { /// {
/// public static void Main(string[] args) /// public static void Main(string[] args)
/// { /// {
/// var config = WebApplicationConfiguration.GetDefault(args); /// var config = WebHostConfiguration.GetDefault(args);
/// ///
/// var application = new WebApplicationBuilder() /// var host = new WebHostBuilder()
/// .UseConfiguration(config) /// .UseConfiguration(config)
/// .Build(); /// .Build();
/// ///
/// // This call will block until the service is stopped. /// // This call will block until the service is stopped.
/// application.RunAsService(); /// host.RunAsService();
/// } /// }
/// } /// }
/// </code> /// </code>
/// </example> /// </example>
public static void RunAsService(this IWebApplication application) public static void RunAsService(this IWebHost host)
{ {
var webApplicationService = new WebApplicationService(application); var webHostService = new WebHostService(host);
ServiceBase.Run(webApplicationService); ServiceBase.Run(webHostService);
} }
} }
} }

View File

@ -11,7 +11,7 @@ namespace Microsoft.AspNet.Hosting.Internal
{ {
public static class HostingEnvironmentExtensions public static class HostingEnvironmentExtensions
{ {
public static void Initialize(this IHostingEnvironment hostingEnvironment, string applicationBasePath, WebApplicationOptions options, IConfiguration configuration) public static void Initialize(this IHostingEnvironment hostingEnvironment, string applicationBasePath, WebHostOptions options, IConfiguration configuration)
{ {
if (options == null) if (options == null)
{ {

View File

@ -19,17 +19,17 @@ using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNet.Hosting.Internal namespace Microsoft.AspNet.Hosting.Internal
{ {
public class WebApplication : IWebApplication public class WebHost : IWebHost
{ {
private readonly IServiceCollection _applicationServiceCollection; private readonly IServiceCollection _applicationServiceCollection;
private readonly IStartupLoader _startupLoader; private readonly IStartupLoader _startupLoader;
private readonly ApplicationLifetime _applicationLifetime; private readonly ApplicationLifetime _applicationLifetime;
private readonly WebApplicationOptions _options; private readonly WebHostOptions _options;
private readonly IConfiguration _config; private readonly IConfiguration _config;
private IServiceProvider _applicationServices; private IServiceProvider _applicationServices;
private RequestDelegate _application; private RequestDelegate _application;
private ILogger<WebApplication> _logger; private ILogger<WebHost> _logger;
// Only one of these should be set // Only one of these should be set
internal string StartupAssemblyName { get; set; } internal string StartupAssemblyName { get; set; }
@ -41,10 +41,10 @@ namespace Microsoft.AspNet.Hosting.Internal
internal string ServerFactoryLocation { get; set; } internal string ServerFactoryLocation { get; set; }
private IServer Server { get; set; } private IServer Server { get; set; }
public WebApplication( public WebHost(
IServiceCollection appServices, IServiceCollection appServices,
IStartupLoader startupLoader, IStartupLoader startupLoader,
WebApplicationOptions options, WebHostOptions options,
IConfiguration config) IConfiguration config)
{ {
if (appServices == null) if (appServices == null)
@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Hosting.Internal
{ {
Initialize(); Initialize();
_logger = _applicationServices.GetRequiredService<ILogger<WebApplication>>(); _logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
var diagnosticSource = _applicationServices.GetRequiredService<DiagnosticSource>(); var diagnosticSource = _applicationServices.GetRequiredService<DiagnosticSource>();
var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>(); var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>();
@ -183,7 +183,7 @@ namespace Microsoft.AspNet.Hosting.Internal
// Write errors to standard out so they can be retrieved when not in development mode. // Write errors to standard out so they can be retrieved when not in development mode.
Console.Out.WriteLine("Application startup exception: " + ex.ToString()); Console.Out.WriteLine("Application startup exception: " + ex.ToString());
var logger = _applicationServices.GetRequiredService<ILogger<WebApplication>>(); var logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
logger.ApplicationError(ex); logger.ApplicationError(ex);
// Generate an HTML error page. // Generate an HTML error page.

View File

@ -6,28 +6,28 @@ using Microsoft.Extensions.Configuration;
namespace Microsoft.AspNet.Hosting.Internal namespace Microsoft.AspNet.Hosting.Internal
{ {
public class WebApplicationOptions public class WebHostOptions
{ {
private const string OldEnvironmentKey = "ENV"; private const string OldEnvironmentKey = "ENV";
public WebApplicationOptions() public WebHostOptions()
{ {
} }
public WebApplicationOptions(IConfiguration configuration) public WebHostOptions(IConfiguration configuration)
{ {
if (configuration == null) if (configuration == null)
{ {
throw new ArgumentNullException(nameof(configuration)); throw new ArgumentNullException(nameof(configuration));
} }
Application = configuration[WebApplicationDefaults.ApplicationKey]; Application = configuration[WebHostDefaults.ApplicationKey];
DetailedErrors = ParseBool(configuration, WebApplicationDefaults.DetailedErrorsKey); DetailedErrors = ParseBool(configuration, WebHostDefaults.DetailedErrorsKey);
CaptureStartupErrors = ParseBool(configuration, WebApplicationDefaults.CaptureStartupErrorsKey); CaptureStartupErrors = ParseBool(configuration, WebHostDefaults.CaptureStartupErrorsKey);
Environment = configuration[WebApplicationDefaults.EnvironmentKey] ?? configuration[OldEnvironmentKey]; Environment = configuration[WebHostDefaults.EnvironmentKey] ?? configuration[OldEnvironmentKey];
ServerFactoryLocation = configuration[WebApplicationDefaults.ServerKey]; ServerFactoryLocation = configuration[WebHostDefaults.ServerKey];
WebRoot = configuration[WebApplicationDefaults.WebRootKey]; WebRoot = configuration[WebHostDefaults.WebRootKey];
ApplicationBasePath = configuration[WebApplicationDefaults.ApplicationBaseKey]; ApplicationBasePath = configuration[WebHostDefaults.ApplicationBaseKey];
} }
public string Application { get; set; } public string Application { get; set; }

View File

@ -1,181 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.AspNet.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNet.Hosting
{
public static class WebApplicationBuilderExtensions
{
private static readonly string ServerUrlsSeparator = ";";
public static IWebApplicationBuilder UseCaptureStartupErrors(this IWebApplicationBuilder applicationBuilder, bool captureStartupError)
{
return applicationBuilder.UseSetting(WebApplicationDefaults.CaptureStartupErrorsKey, captureStartupError ? "true" : "false");
}
public static IWebApplicationBuilder UseStartup<TStartup>(this IWebApplicationBuilder applicationBuilder) where TStartup : class
{
return applicationBuilder.UseStartup(typeof(TStartup));
}
public static IWebApplicationBuilder UseServer(this IWebApplicationBuilder applicationBuilder, string assemblyName)
{
if (assemblyName == null)
{
throw new ArgumentNullException(nameof(assemblyName));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.ServerKey, assemblyName);
}
public static IWebApplicationBuilder UseServer(this IWebApplicationBuilder applicationBuilder, IServer server)
{
if (server == null)
{
throw new ArgumentNullException(nameof(server));
}
return applicationBuilder.UseServer(new ServerFactory(server));
}
public static IWebApplicationBuilder UseApplicationBasePath(this IWebApplicationBuilder applicationBuilder, string applicationBasePath)
{
if (applicationBasePath == null)
{
throw new ArgumentNullException(nameof(applicationBasePath));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.ApplicationBaseKey, applicationBasePath);
}
public static IWebApplicationBuilder UseEnvironment(this IWebApplicationBuilder applicationBuilder, string environment)
{
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.EnvironmentKey, environment);
}
public static IWebApplicationBuilder UseWebRoot(this IWebApplicationBuilder applicationBuilder, string webRoot)
{
if (webRoot == null)
{
throw new ArgumentNullException(nameof(webRoot));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.WebRootKey, webRoot);
}
public static IWebApplicationBuilder UseUrls(this IWebApplicationBuilder applicationBuilder, params string[] urls)
{
if (urls == null)
{
throw new ArgumentNullException(nameof(urls));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.ServerUrlsKey, string.Join(ServerUrlsSeparator, urls));
}
public static IWebApplicationBuilder UseStartup(this IWebApplicationBuilder applicationBuilder, string startupAssemblyName)
{
if (startupAssemblyName == null)
{
throw new ArgumentNullException(nameof(startupAssemblyName));
}
return applicationBuilder.UseSetting(WebApplicationDefaults.ApplicationKey, startupAssemblyName);
}
public static IWebApplication Start(this IWebApplicationBuilder applicationBuilder, params string[] urls)
{
var application = applicationBuilder.UseUrls(urls).Build();
application.Start();
return application;
}
/// <summary>
/// Runs a web application and block the calling thread until host shutdown.
/// </summary>
/// <param name="application"></param>
public static void Run(this IWebApplication application)
{
using (var cts = new CancellationTokenSource())
{
Console.CancelKeyPress += (sender, eventArgs) =>
{
cts.Cancel();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
application.Run(cts.Token, "Application started. Press Ctrl+C to shut down.");
}
}
/// <summary>
/// Runs a web application and block the calling thread until token is triggered or shutdown is triggered
/// </summary>
/// <param name="application"></param>
/// <param name="token">The token to trigger shutdown</param>
public static void Run(this IWebApplication application, CancellationToken token)
{
application.Run(token, shutdownMessage: null);
}
private static void Run(this IWebApplication application, CancellationToken token, string shutdownMessage)
{
using (application)
{
application.Start();
var hostingEnvironment = application.Services.GetService<IHostingEnvironment>();
var applicationLifetime = application.Services.GetService<IApplicationLifetime>();
Console.WriteLine("Hosting environment: " + hostingEnvironment.EnvironmentName);
var serverAddresses = application.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
if (serverAddresses != null)
{
foreach (var address in serverAddresses)
{
Console.WriteLine("Now listening on: " + address);
}
}
if (!string.IsNullOrEmpty(shutdownMessage))
{
Console.WriteLine(shutdownMessage);
}
token.Register(state =>
{
((IApplicationLifetime)state).StopApplication();
},
applicationLifetime);
applicationLifetime.ApplicationStopping.WaitHandle.WaitOne();
}
}
private class ServerFactory : IServerFactory
{
private readonly IServer _server;
public ServerFactory(IServer server)
{
_server = server;
}
public IServer CreateServer(IConfiguration configuration) => _server;
}
}
}

View File

@ -20,13 +20,16 @@ using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
public class WebApplicationBuilder : IWebApplicationBuilder /// <summary>
/// A builder for <see cref="IWebHost"/>
/// </summary>
public class WebHostBuilder : IWebHostBuilder
{ {
private readonly IHostingEnvironment _hostingEnvironment; private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILoggerFactory _loggerFactory; private readonly ILoggerFactory _loggerFactory;
private IConfiguration _config; private IConfiguration _config;
private WebApplicationOptions _options; private WebHostOptions _options;
private Action<IServiceCollection> _configureServices; private Action<IServiceCollection> _configureServices;
@ -39,12 +42,16 @@ namespace Microsoft.AspNet.Hosting
private IDictionary<string, string> _settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private IDictionary<string, string> _settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public WebApplicationBuilder() public WebHostBuilder()
{ {
_hostingEnvironment = new HostingEnvironment(); _hostingEnvironment = new HostingEnvironment();
_loggerFactory = new LoggerFactory(); _loggerFactory = new LoggerFactory();
} }
/// <summary>
/// Gets the raw settings to be used by the web host. Values specified here will override
/// the configuration set by <see cref="UseConfiguration(IConfiguration)"/>.
/// </summary>
public IDictionary<string, string> Settings public IDictionary<string, string> Settings
{ {
get get
@ -53,19 +60,36 @@ namespace Microsoft.AspNet.Hosting
} }
} }
public IWebApplicationBuilder UseSetting(string key, string value) /// <summary>
/// Add or replace a setting in <see cref="Settings"/>.
/// </summary>
/// <param name="key">The key of the setting to add or replace.</param>
/// <param name="value">The value of the setting to add or replace.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseSetting(string key, string value)
{ {
_settings[key] = value; _settings[key] = value;
return this; return this;
} }
public IWebApplicationBuilder UseConfiguration(IConfiguration configuration) /// <summary>
/// Specify the <see cref="IConfiguration"/> to be used by the web host. If no configuration is
/// provided to the builder, the default configuration will be used.
/// </summary>
/// <param name="configuration">The <see cref="IConfiguration"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseConfiguration(IConfiguration configuration)
{ {
_config = configuration; _config = configuration;
return this; return this;
} }
public IWebApplicationBuilder UseServer(IServerFactory factory) /// <summary>
/// Specify the <see cref="IServerFactory"/> to be used by the web host.
/// </summary>
/// <param name="factory">The <see cref="IServerFactory"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseServer(IServerFactory factory)
{ {
if (factory == null) if (factory == null)
{ {
@ -76,7 +100,12 @@ namespace Microsoft.AspNet.Hosting
return this; return this;
} }
public IWebApplicationBuilder UseStartup(Type startupType) /// <summary>
/// Specify the startup type to be used by the web host.
/// </summary>
/// <param name="startupType">The <see cref="Type"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseStartup(Type startupType)
{ {
if (startupType == null) if (startupType == null)
{ {
@ -87,13 +116,23 @@ namespace Microsoft.AspNet.Hosting
return this; return this;
} }
public IWebApplicationBuilder ConfigureServices(Action<IServiceCollection> configureServices) /// <summary>
/// Specify the delegate that is used to configure the services of the web application.
/// </summary>
/// <param name="configureServices">The delegate that configures the <see cref="IServiceCollection"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices)
{ {
_configureServices = configureServices; _configureServices = configureServices;
return this; return this;
} }
public IWebApplicationBuilder Configure(Action<IApplicationBuilder> configureApp) /// <summary>
/// Specify the startup method to be used to configure the web application.
/// </summary>
/// <param name="configureApplication">The delegate that configures the <see cref="IApplicationBuilder"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder Configure(Action<IApplicationBuilder> configureApp)
{ {
if (configureApp == null) if (configureApp == null)
{ {
@ -104,13 +143,21 @@ namespace Microsoft.AspNet.Hosting
return this; return this;
} }
public IWebApplicationBuilder ConfigureLogging(Action<ILoggerFactory> configureLogging) /// <summary>
/// Configure the provided <see cref="ILoggerFactory"/> which will be available as a hosting service.
/// </summary>
/// <param name="configureLogging">The delegate that configures the <see cref="ILoggerFactory"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder ConfigureLogging(Action<ILoggerFactory> configureLogging)
{ {
configureLogging(_loggerFactory); configureLogging(_loggerFactory);
return this; return this;
} }
public IWebApplication Build() /// <summary>
/// Builds the required services and an <see cref="IWebHost"/> which hosts a web application.
/// </summary>
public IWebHost Build()
{ {
var hostingServices = BuildHostingServices(); var hostingServices = BuildHostingServices();
@ -122,26 +169,26 @@ namespace Microsoft.AspNet.Hosting
// Initialize the hosting environment // Initialize the hosting environment
_hostingEnvironment.Initialize(appEnvironment.ApplicationBasePath, _options, _config); _hostingEnvironment.Initialize(appEnvironment.ApplicationBasePath, _options, _config);
var application = new WebApplication(hostingServices, startupLoader, _options, _config); var host = new WebHost(hostingServices, startupLoader, _options, _config);
// Only one of these should be set, but they are used in priority // Only one of these should be set, but they are used in priority
application.ServerFactory = _serverFactory; host.ServerFactory = _serverFactory;
application.ServerFactoryLocation = _options.ServerFactoryLocation; host.ServerFactoryLocation = _options.ServerFactoryLocation;
// Only one of these should be set, but they are used in priority // Only one of these should be set, but they are used in priority
application.Startup = _startup; host.Startup = _startup;
application.StartupType = _startupType; host.StartupType = _startupType;
application.StartupAssemblyName = _options.Application; host.StartupAssemblyName = _options.Application;
application.Initialize(); host.Initialize();
return application; return host;
} }
private IServiceCollection BuildHostingServices() private IServiceCollection BuildHostingServices()
{ {
// Apply the configuration settings // Apply the configuration settings
var configuration = _config ?? WebApplicationConfiguration.GetDefault(); var configuration = _config ?? WebHostConfiguration.GetDefault();
var mergedConfiguration = new ConfigurationBuilder() var mergedConfiguration = new ConfigurationBuilder()
.Add(new IncludedConfigurationProvider(configuration)) .Add(new IncludedConfigurationProvider(configuration))
@ -149,7 +196,7 @@ namespace Microsoft.AspNet.Hosting
.Build(); .Build();
_config = mergedConfiguration; _config = mergedConfiguration;
_options = new WebApplicationOptions(_config); _options = new WebHostOptions(_config);
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddSingleton(_hostingEnvironment); services.AddSingleton(_hostingEnvironment);

View File

@ -0,0 +1,123 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Hosting.Server;
using Microsoft.Extensions.Configuration;
namespace Microsoft.AspNet.Hosting
{
public static class WebHostBuilderExtensions
{
private static readonly string ServerUrlsSeparator = ";";
public static IWebHostBuilder UseDefaultConfiguration(this IWebHostBuilder builder)
{
return builder.UseDefaultConfiguration(args: null);
}
public static IWebHostBuilder UseDefaultConfiguration(this IWebHostBuilder builder, string[] args)
{
return builder.UseConfiguration(WebHostConfiguration.GetDefault(args));
}
public static IWebHostBuilder UseCaptureStartupErrors(this IWebHostBuilder hostBuilder, bool captureStartupError)
{
return hostBuilder.UseSetting(WebHostDefaults.CaptureStartupErrorsKey, captureStartupError ? "true" : "false");
}
public static IWebHostBuilder UseStartup<TStartup>(this IWebHostBuilder hostBuilder) where TStartup : class
{
return hostBuilder.UseStartup(typeof(TStartup));
}
public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, string assemblyName)
{
if (assemblyName == null)
{
throw new ArgumentNullException(nameof(assemblyName));
}
return hostBuilder.UseSetting(WebHostDefaults.ServerKey, assemblyName);
}
public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, IServer server)
{
if (server == null)
{
throw new ArgumentNullException(nameof(server));
}
return hostBuilder.UseServer(new ServerFactory(server));
}
public static IWebHostBuilder UseApplicationBasePath(this IWebHostBuilder hostBuilder, string applicationBasePath)
{
if (applicationBasePath == null)
{
throw new ArgumentNullException(nameof(applicationBasePath));
}
return hostBuilder.UseSetting(WebHostDefaults.ApplicationBaseKey, applicationBasePath);
}
public static IWebHostBuilder UseEnvironment(this IWebHostBuilder hostBuilder, string environment)
{
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
return hostBuilder.UseSetting(WebHostDefaults.EnvironmentKey, environment);
}
public static IWebHostBuilder UseWebRoot(this IWebHostBuilder hostBuilder, string webRoot)
{
if (webRoot == null)
{
throw new ArgumentNullException(nameof(webRoot));
}
return hostBuilder.UseSetting(WebHostDefaults.WebRootKey, webRoot);
}
public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, params string[] urls)
{
if (urls == null)
{
throw new ArgumentNullException(nameof(urls));
}
return hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Join(ServerUrlsSeparator, urls));
}
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, string startupAssemblyName)
{
if (startupAssemblyName == null)
{
throw new ArgumentNullException(nameof(startupAssemblyName));
}
return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName);
}
public static IWebHost Start(this IWebHostBuilder hostBuilder, params string[] urls)
{
var host = hostBuilder.UseUrls(urls).Build();
host.Start();
return host;
}
private class ServerFactory : IServerFactory
{
private readonly IServer _server;
public ServerFactory(IServer server)
{
_server = server;
}
public IServer CreateServer(IConfiguration configuration) => _server;
}
}
}

View File

@ -6,7 +6,7 @@ using Microsoft.Extensions.Configuration;
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
public class WebApplicationConfiguration public class WebHostConfiguration
{ {
public static IConfiguration GetDefault() public static IConfiguration GetDefault()
{ {
@ -17,16 +17,16 @@ namespace Microsoft.AspNet.Hosting
{ {
var defaultSettings = new Dictionary<string, string> var defaultSettings = new Dictionary<string, string>
{ {
{ WebApplicationDefaults.CaptureStartupErrorsKey, "true" } { WebHostDefaults.CaptureStartupErrorsKey, "true" }
}; };
// We are adding all environment variables first and then adding the ASPNET_ ones // We are adding all environment variables first and then adding the ASPNET_ ones
// with the prefix removed to unify with the command line and config file formats // with the prefix removed to unify with the command line and config file formats
var configBuilder = new ConfigurationBuilder() var configBuilder = new ConfigurationBuilder()
.AddInMemoryCollection(defaultSettings) .AddInMemoryCollection(defaultSettings)
.AddJsonFile(WebApplicationDefaults.HostingJsonFile, optional: true) .AddJsonFile(WebHostDefaults.HostingJsonFile, optional: true)
.AddEnvironmentVariables() .AddEnvironmentVariables()
.AddEnvironmentVariables(prefix: WebApplicationDefaults.EnvironmentVariablesPrefix); .AddEnvironmentVariables(prefix: WebHostDefaults.EnvironmentVariablesPrefix);
if (args != null) if (args != null)
{ {

View File

@ -0,0 +1,78 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using Microsoft.AspNet.Server.Features;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNet.Hosting
{
public static class WebHostExtensions
{
/// <summary>
/// Runs a web application and block the calling thread until host shutdown.
/// </summary>
/// <param name="host"></param>
public static void Run(this IWebHost host)
{
using (var cts = new CancellationTokenSource())
{
Console.CancelKeyPress += (sender, eventArgs) =>
{
cts.Cancel();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
host.Run(cts.Token, "Application started. Press Ctrl+C to shut down.");
}
}
/// <summary>
/// Runs a web application and block the calling thread until token is triggered or shutdown is triggered
/// </summary>
/// <param name="host"></param>
/// <param name="token">The token to trigger shutdown</param>
public static void Run(this IWebHost host, CancellationToken token)
{
host.Run(token, shutdownMessage: null);
}
private static void Run(this IWebHost host, CancellationToken token, string shutdownMessage)
{
using (host)
{
host.Start();
var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
var applicationLifetime = host.Services.GetService<IApplicationLifetime>();
Console.WriteLine("Hosting environment: " + hostingEnvironment.EnvironmentName);
var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
if (serverAddresses != null)
{
foreach (var address in serverAddresses)
{
Console.WriteLine("Now listening on: " + address);
}
}
if (!string.IsNullOrEmpty(shutdownMessage))
{
Console.WriteLine(shutdownMessage);
}
token.Register(state =>
{
((IApplicationLifetime)state).StopApplication();
},
applicationLifetime);
applicationLifetime.ApplicationStopping.WaitHandle.WaitOne();
}
}
}
}

View File

@ -16,29 +16,29 @@ namespace Microsoft.AspNet.TestHost
{ {
private const string DefaultEnvironmentName = "Development"; private const string DefaultEnvironmentName = "Development";
private const string ServerName = nameof(TestServer); private const string ServerName = nameof(TestServer);
private IWebApplication _appInstance; private IWebHost _hostInstance;
private bool _disposed = false; private bool _disposed = false;
private IHttpApplication<Context> _application; private IHttpApplication<Context> _application;
public TestServer(IWebApplicationBuilder builder) public TestServer(IWebHostBuilder builder)
{ {
if (!builder.Settings.ContainsKey(WebApplicationDefaults.CaptureStartupErrorsKey)) if (!builder.Settings.ContainsKey(WebHostDefaults.CaptureStartupErrorsKey))
{ {
builder.UseCaptureStartupErrors(false); builder.UseCaptureStartupErrors(false);
} }
var application = builder.UseServer(this).Build(); var host = builder.UseServer(this).Build();
application.Start(); host.Start();
_appInstance = application; _hostInstance = host;
} }
public Uri BaseAddress { get; set; } = new Uri("http://localhost/"); public Uri BaseAddress { get; set; } = new Uri("http://localhost/");
public IWebApplication Application public IWebHost Host
{ {
get get
{ {
return _appInstance; return _hostInstance;
} }
} }
@ -76,7 +76,7 @@ namespace Microsoft.AspNet.TestHost
if (!_disposed) if (!_disposed)
{ {
_disposed = true; _disposed = true;
_appInstance.Dispose(); _hostInstance.Dispose();
} }
} }

View File

@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Hosting.Tests
{ {
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.Initialize(".", new WebApplicationOptions() {WebRoot = "testroot"}, null); env.Initialize(".", new WebHostOptions() {WebRoot = "testroot"}, null);
Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath); Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider); Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider);
@ -28,7 +28,7 @@ namespace Microsoft.AspNet.Hosting.Tests
{ {
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.Initialize("testroot", new WebApplicationOptions(), null); env.Initialize("testroot", new WebHostOptions(), null);
Assert.Equal(Path.GetFullPath(Path.Combine("testroot","wwwroot")), env.WebRootPath); Assert.Equal(Path.GetFullPath(Path.Combine("testroot","wwwroot")), env.WebRootPath);
Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider); Assert.IsAssignableFrom<PhysicalFileProvider>(env.WebRootFileProvider);
@ -39,7 +39,7 @@ namespace Microsoft.AspNet.Hosting.Tests
{ {
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.Initialize(Path.Combine("testroot", "wwwroot"), new WebApplicationOptions(), null); env.Initialize(Path.Combine("testroot", "wwwroot"), new WebHostOptions(), null);
Assert.Null(env.WebRootPath); Assert.Null(env.WebRootPath);
Assert.IsAssignableFrom<NullFileProvider>(env.WebRootFileProvider); Assert.IsAssignableFrom<NullFileProvider>(env.WebRootFileProvider);
@ -51,7 +51,7 @@ namespace Microsoft.AspNet.Hosting.Tests
var config = new ConfigurationBuilder().Build(); var config = new ConfigurationBuilder().Build();
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.Initialize(".", new WebApplicationOptions(), config); env.Initialize(".", new WebHostOptions(), config);
Assert.Same(config, env.Configuration); Assert.Same(config, env.Configuration);
} }
@ -62,7 +62,7 @@ namespace Microsoft.AspNet.Hosting.Tests
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.EnvironmentName = "SomeName"; env.EnvironmentName = "SomeName";
env.Initialize(".", new WebApplicationOptions() { Environment = "NewName" }, null); env.Initialize(".", new WebHostOptions() { Environment = "NewName" }, null);
Assert.Equal("NewName", env.EnvironmentName); Assert.Equal("NewName", env.EnvironmentName);
} }
@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Hosting.Tests
{ {
var env = new HostingEnvironment(); var env = new HostingEnvironment();
env.Initialize(".", new WebApplicationOptions(), null); env.Initialize(".", new WebHostOptions(), null);
Assert.Throws<InvalidOperationException>(() => env.MapPath("file.txt")); Assert.Throws<InvalidOperationException>(() => env.MapPath("file.txt"));
} }

View File

@ -18,27 +18,27 @@ using Xunit;
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
public class WebApplicationBuilderTests public class WebHostBuilderTests
{ {
[Fact] [Fact]
public void Build_honors_UseStartup_with_string() public void Build_honors_UseStartup_with_string()
{ {
var builder = CreateWebApplicationBuilder().UseServer(new TestServer()); var builder = CreateWebHostBuilder().UseServer(new TestServer());
var application = (WebApplication)builder.UseStartup("MyStartupAssembly").Build(); var host = (WebHost)builder.UseStartup("MyStartupAssembly").Build();
Assert.Equal("MyStartupAssembly", application.StartupAssemblyName); Assert.Equal("MyStartupAssembly", host.StartupAssemblyName);
} }
[Fact] [Fact]
public async Task StartupMissing_Fallback() public async Task StartupMissing_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup("MissingStartupAssembly").Build(); var host = builder.UseServer(server).UseStartup("MissingStartupAssembly").Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "MissingStartupAssembly"); await AssertResponseContains(server.RequestDelegate, "MissingStartupAssembly");
} }
} }
@ -46,12 +46,12 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task StartupStaticCtorThrows_Fallback() public async Task StartupStaticCtorThrows_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupStaticCtorThrows>().Build(); var host = builder.UseServer(server).UseStartup<StartupStaticCtorThrows>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "Exception from static constructor"); await AssertResponseContains(server.RequestDelegate, "Exception from static constructor");
} }
} }
@ -59,12 +59,12 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task StartupCtorThrows_Fallback() public async Task StartupCtorThrows_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupCtorThrows>().Build(); var host = builder.UseServer(server).UseStartup<StartupCtorThrows>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "Exception from constructor"); await AssertResponseContains(server.RequestDelegate, "Exception from constructor");
} }
} }
@ -72,12 +72,12 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task StartupCtorThrows_TypeLoadException() public async Task StartupCtorThrows_TypeLoadException()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupThrowTypeLoadException>().Build(); var host = builder.UseServer(server).UseStartup<StartupThrowTypeLoadException>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "Message from the LoaderException</span>"); await AssertResponseContains(server.RequestDelegate, "Message from the LoaderException</span>");
} }
} }
@ -85,13 +85,13 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task IApplicationLifetimeRegisteredEvenWhenStartupCtorThrows_Fallback() public async Task IApplicationLifetimeRegisteredEvenWhenStartupCtorThrows_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupCtorThrows>().Build(); var host = builder.UseServer(server).UseStartup<StartupCtorThrows>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
var service = application.Services.GetServices<IApplicationLifetime>(); var service = host.Services.GetServices<IApplicationLifetime>();
Assert.NotNull(service); Assert.NotNull(service);
await AssertResponseContains(server.RequestDelegate, "Exception from constructor"); await AssertResponseContains(server.RequestDelegate, "Exception from constructor");
} }
@ -100,12 +100,12 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task StartupConfigureServicesThrows_Fallback() public async Task StartupConfigureServicesThrows_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupConfigureServicesThrows>().Build(); var host = builder.UseServer(server).UseStartup<StartupConfigureServicesThrows>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "Exception from ConfigureServices"); await AssertResponseContains(server.RequestDelegate, "Exception from ConfigureServices");
} }
} }
@ -113,12 +113,12 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public async Task StartupConfigureThrows_Fallback() public async Task StartupConfigureThrows_Fallback()
{ {
var builder = CreateWebApplicationBuilder(); var builder = CreateWebHostBuilder();
var server = new TestServer(); var server = new TestServer();
var application = builder.UseServer(server).UseStartup<StartupConfigureServicesThrows>().Build(); var host = builder.UseServer(server).UseStartup<StartupConfigureServicesThrows>().Build();
using (application) using (host)
{ {
application.Start(); host.Start();
await AssertResponseContains(server.RequestDelegate, "Exception from Configure"); await AssertResponseContains(server.RequestDelegate, "Exception from Configure");
} }
} }
@ -126,23 +126,23 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public void CaptureStartupErrorsByDefault() public void CaptureStartupErrorsByDefault()
{ {
var applicationBuilder = new WebApplicationBuilder() var hostBuilder = new WebHostBuilder()
.UseServer(new TestServer()) .UseServer(new TestServer())
.UseStartup<StartupBoom>(); .UseStartup<StartupBoom>();
// This should not throw // This should not throw
applicationBuilder.Build(); hostBuilder.Build();
} }
[Fact] [Fact]
public void UseCaptureStartupErrorsHonored() public void UseCaptureStartupErrorsHonored()
{ {
var applicationBuilder = new WebApplicationBuilder() var hostBuilder = new WebHostBuilder()
.UseCaptureStartupErrors(false) .UseCaptureStartupErrors(false)
.UseServer(new TestServer()) .UseServer(new TestServer())
.UseStartup<StartupBoom>(); .UseStartup<StartupBoom>();
var exception = Assert.Throws<InvalidOperationException>(() => applicationBuilder.Build()); var exception = Assert.Throws<InvalidOperationException>(() => hostBuilder.Build());
Assert.Equal("A public method named 'ConfigureProduction' or 'Configure' could not be found in the 'Microsoft.AspNet.Hosting.Fakes.StartupBoom' type.", exception.Message); Assert.Equal("A public method named 'ConfigureProduction' or 'Configure' could not be found in the 'Microsoft.AspNet.Hosting.Fakes.StartupBoom' type.", exception.Message);
} }
@ -158,14 +158,14 @@ namespace Microsoft.AspNet.Hosting
var config = builder.Build(); var config = builder.Build();
var expected = "MY_TEST_ENVIRONMENT"; var expected = "MY_TEST_ENVIRONMENT";
var application = new WebApplicationBuilder() var host = new WebHostBuilder()
.UseConfiguration(config) .UseConfiguration(config)
.UseEnvironment(expected) .UseEnvironment(expected)
.UseServer(new TestServer()) .UseServer(new TestServer())
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Build(); .Build();
Assert.Equal(expected, application.Services.GetService<IHostingEnvironment>().EnvironmentName); Assert.Equal(expected, host.Services.GetService<IHostingEnvironment>().EnvironmentName);
} }
[Fact] [Fact]
@ -180,14 +180,14 @@ namespace Microsoft.AspNet.Hosting
var config = builder.Build(); var config = builder.Build();
var expected = "MY_TEST_ENVIRONMENT"; var expected = "MY_TEST_ENVIRONMENT";
var application = new WebApplicationBuilder() var host = new WebHostBuilder()
.UseConfiguration(config) .UseConfiguration(config)
.UseEnvironment(expected) .UseEnvironment(expected)
.UseServer(new TestServer()) .UseServer(new TestServer())
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Build(); .Build();
application.Dispose(); host.Dispose();
} }
[Fact] [Fact]
@ -201,17 +201,17 @@ namespace Microsoft.AspNet.Hosting
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = new WebApplicationBuilder() var host = new WebHostBuilder()
.UseConfiguration(config) .UseConfiguration(config)
.UseApplicationBasePath("/foo/bar") .UseApplicationBasePath("/foo/bar")
.UseServer(new TestServer()) .UseServer(new TestServer())
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Build(); .Build();
Assert.Equal("/foo/bar", application.Services.GetService<IApplicationEnvironment>().ApplicationBasePath); Assert.Equal("/foo/bar", host.Services.GetService<IApplicationEnvironment>().ApplicationBasePath);
} }
private IWebApplicationBuilder CreateWebApplicationBuilder() private IWebHostBuilder CreateWebHostBuilder()
{ {
var vals = new Dictionary<string, string> var vals = new Dictionary<string, string>
{ {
@ -221,7 +221,7 @@ namespace Microsoft.AspNet.Hosting
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
return new WebApplicationBuilder().UseConfiguration(config); return new WebHostBuilder().UseConfiguration(config);
} }
private async Task AssertResponseContains(RequestDelegate app, string expectedText) private async Task AssertResponseContains(RequestDelegate app, string expectedText)

View File

@ -8,12 +8,12 @@ using Xunit;
namespace Microsoft.AspNet.Hosting.Tests namespace Microsoft.AspNet.Hosting.Tests
{ {
public class WebApplicationConfigurationTests public class WebHostConfigurationTests
{ {
[Fact] [Fact]
public void DefaultCapturesStartupErrors() public void DefaultCapturesStartupErrors()
{ {
var config = new WebApplicationOptions(WebApplicationConfiguration.GetDefault()); var config = new WebHostOptions(WebHostConfiguration.GetDefault());
Assert.True(config.CaptureStartupErrors); Assert.True(config.CaptureStartupErrors);
} }
@ -31,7 +31,7 @@ namespace Microsoft.AspNet.Hosting.Tests
{ "captureStartupErrors", "true" } { "captureStartupErrors", "true" }
}; };
var config = new WebApplicationOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build()); var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build());
Assert.Equal("wwwroot", config.WebRoot); Assert.Equal("wwwroot", config.WebRoot);
Assert.Equal("Microsoft.AspNet.Server.Kestrel", config.ServerFactoryLocation); Assert.Equal("Microsoft.AspNet.Server.Kestrel", config.ServerFactoryLocation);
@ -45,7 +45,7 @@ namespace Microsoft.AspNet.Hosting.Tests
public void ReadsOldEnvKey() public void ReadsOldEnvKey()
{ {
var parameters = new Dictionary<string, string>() { { "ENV", "Development" } }; var parameters = new Dictionary<string, string>() { { "ENV", "Development" } };
var config = new WebApplicationOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build()); var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build());
Assert.Equal("Development", config.Environment); Assert.Equal("Development", config.Environment);
} }
@ -56,7 +56,7 @@ namespace Microsoft.AspNet.Hosting.Tests
public void AllowsNumberForDetailedErrors(string value, bool expected) public void AllowsNumberForDetailedErrors(string value, bool expected)
{ {
var parameters = new Dictionary<string, string>() { { "detailedErrors", value } }; var parameters = new Dictionary<string, string>() { { "detailedErrors", value } };
var config = new WebApplicationOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build()); var config = new WebHostOptions(new ConfigurationBuilder().AddInMemoryCollection(parameters).Build());
Assert.Equal(expected, config.DetailedErrors); Assert.Equal(expected, config.DetailedErrors);
} }

View File

@ -25,7 +25,7 @@ using Xunit;
namespace Microsoft.AspNet.Hosting namespace Microsoft.AspNet.Hosting
{ {
public class WebApplicationTests : IServerFactory, IServer public class WebHostTests : IServerFactory, IServer
{ {
private readonly IList<StartInstance> _startInstances = new List<StartInstance>(); private readonly IList<StartInstance> _startInstances = new List<StartInstance>();
private IFeatureCollection _featuresSupportedByThisHost = NewFeatureCollection(); private IFeatureCollection _featuresSupportedByThisHost = NewFeatureCollection();
@ -64,7 +64,7 @@ namespace Microsoft.AspNet.Hosting
} }
[Fact] [Fact]
public void WebApplicationThrowsWithNoServer() public void WebHostThrowsWithNoServer()
{ {
var ex = Assert.Throws<InvalidOperationException>(() => CreateBuilder().Build().Start()); var ex = Assert.Throws<InvalidOperationException>(() => CreateBuilder().Build().Start());
Assert.True(ex.Message.Contains("UseServer()")); Assert.True(ex.Message.Contains("UseServer()"));
@ -87,9 +87,9 @@ namespace Microsoft.AspNet.Hosting
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).Build(); var host = CreateBuilder(config).Build();
application.Start(); host.Start();
Assert.NotNull(application.Services.GetService<IHostingEnvironment>()); Assert.NotNull(host.Services.GetService<IHostingEnvironment>());
} }
[Fact] [Fact]
@ -103,9 +103,9 @@ namespace Microsoft.AspNet.Hosting
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).Build(); var host = CreateBuilder(config).Build();
application.Start(); host.Start();
Assert.NotNull(application.Services.GetService<IHostingEnvironment>()); Assert.NotNull(host.Services.GetService<IHostingEnvironment>());
} }
[Fact] [Fact]
@ -119,10 +119,10 @@ namespace Microsoft.AspNet.Hosting
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).Build(); var host = CreateBuilder(config).Build();
application.Start(); host.Start();
Assert.NotNull(application.Services.GetService<IHostingEnvironment>()); Assert.NotNull(host.Services.GetService<IHostingEnvironment>());
Assert.Equal("http://localhost:5000", application.ServerFeatures.Get<IServerAddressesFeature>().Addresses.First()); Assert.Equal("http://localhost:5000", host.ServerFeatures.Get<IServerAddressesFeature>().Addresses.First());
} }
[Fact] [Fact]
@ -136,45 +136,45 @@ namespace Microsoft.AspNet.Hosting
var builder = new ConfigurationBuilder() var builder = new ConfigurationBuilder()
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).Build(); var host = CreateBuilder(config).Build();
application.Start(); host.Start();
var hostingEnvironment = application.Services.GetService<IHostingEnvironment>(); var hostingEnvironment = host.Services.GetService<IHostingEnvironment>();
Assert.NotNull(hostingEnvironment.Configuration); Assert.NotNull(hostingEnvironment.Configuration);
Assert.Equal("Microsoft.AspNet.Hosting.Tests", hostingEnvironment.Configuration["Server"]); Assert.Equal("Microsoft.AspNet.Hosting.Tests", hostingEnvironment.Configuration["Server"]);
} }
[Fact] [Fact]
public void WebApplicationCanBeStarted() public void WebHostCanBeStarted()
{ {
var app = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Start(); .Start();
Assert.NotNull(app); Assert.NotNull(host);
Assert.Equal(1, _startInstances.Count); Assert.Equal(1, _startInstances.Count);
Assert.Equal(0, _startInstances[0].DisposeCalls); Assert.Equal(0, _startInstances[0].DisposeCalls);
app.Dispose(); host.Dispose();
Assert.Equal(1, _startInstances[0].DisposeCalls); Assert.Equal(1, _startInstances[0].DisposeCalls);
} }
[Fact] [Fact]
public void WebApplicationShutsDownWhenTokenTriggers() public void WebHostShutsDownWhenTokenTriggers()
{ {
var app = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Build(); .Build();
var lifetime = app.Services.GetRequiredService<IApplicationLifetime>(); var lifetime = host.Services.GetRequiredService<IApplicationLifetime>();
var cts = new CancellationTokenSource(); var cts = new CancellationTokenSource();
Task.Run(() => app.Run(cts.Token)); Task.Run(() => host.Run(cts.Token));
// Wait on the app to be started // Wait on the host to be started
lifetime.ApplicationStarted.WaitHandle.WaitOne(); lifetime.ApplicationStarted.WaitHandle.WaitOne();
Assert.Equal(1, _startInstances.Count); Assert.Equal(1, _startInstances.Count);
@ -182,16 +182,16 @@ namespace Microsoft.AspNet.Hosting
cts.Cancel(); cts.Cancel();
// Wait on the app to shutdown // Wait on the host to shutdown
lifetime.ApplicationStopped.WaitHandle.WaitOne(); lifetime.ApplicationStopped.WaitHandle.WaitOne();
Assert.Equal(1, _startInstances[0].DisposeCalls); Assert.Equal(1, _startInstances[0].DisposeCalls);
} }
[Fact] [Fact]
public void WebApplicationDisposesServiceProvider() public void WebHostDisposesServiceProvider()
{ {
var application = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.ConfigureServices(s => .ConfigureServices(s =>
{ {
@ -201,49 +201,49 @@ namespace Microsoft.AspNet.Hosting
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.Build(); .Build();
application.Start(); host.Start();
var singleton = (FakeService)application.Services.GetService<IFakeSingletonService>(); var singleton = (FakeService)host.Services.GetService<IFakeSingletonService>();
var transient = (FakeService)application.Services.GetService<IFakeService>(); var transient = (FakeService)host.Services.GetService<IFakeService>();
Assert.False(singleton.Disposed); Assert.False(singleton.Disposed);
Assert.False(transient.Disposed); Assert.False(transient.Disposed);
application.Dispose(); host.Dispose();
Assert.True(singleton.Disposed); Assert.True(singleton.Disposed);
Assert.True(transient.Disposed); Assert.True(transient.Disposed);
} }
[Fact] [Fact]
public void WebApplicationNotifiesApplicationStarted() public void WebHostNotifiesApplicationStarted()
{ {
var application = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.Build(); .Build();
var applicationLifetime = application.Services.GetService<IApplicationLifetime>(); var applicationLifetime = host.Services.GetService<IApplicationLifetime>();
Assert.False(applicationLifetime.ApplicationStarted.IsCancellationRequested); Assert.False(applicationLifetime.ApplicationStarted.IsCancellationRequested);
using (application) using (host)
{ {
application.Start(); host.Start();
Assert.True(applicationLifetime.ApplicationStarted.IsCancellationRequested); Assert.True(applicationLifetime.ApplicationStarted.IsCancellationRequested);
} }
} }
[Fact] [Fact]
public void WebApplicationInjectsHostingEnvironment() public void WebHostInjectsHostingEnvironment()
{ {
var application = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.UseStartup("Microsoft.AspNet.Hosting.Tests") .UseStartup("Microsoft.AspNet.Hosting.Tests")
.UseEnvironment("WithHostingEnvironment") .UseEnvironment("WithHostingEnvironment")
.Build(); .Build();
using (application) using (host)
{ {
application.Start(); host.Start();
var env = application.Services.GetService<IHostingEnvironment>(); var env = host.Services.GetService<IHostingEnvironment>();
Assert.Equal("Changed", env.EnvironmentName); Assert.Equal("Changed", env.EnvironmentName);
} }
} }
@ -265,15 +265,15 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public void CanCreateApplicationServicesWithAddedServices() public void CanCreateApplicationServicesWithAddedServices()
{ {
var application = CreateBuilder().UseServer((IServerFactory)this).ConfigureServices(services => services.AddOptions()).Build(); var host = CreateBuilder().UseServer((IServerFactory)this).ConfigureServices(services => services.AddOptions()).Build();
Assert.NotNull(application.Services.GetRequiredService<IOptions<object>>()); Assert.NotNull(host.Services.GetRequiredService<IOptions<object>>());
} }
[Fact] [Fact]
public void EnvDefaultsToProductionIfNoConfig() public void EnvDefaultsToProductionIfNoConfig()
{ {
var application = CreateBuilder().UseServer((IServerFactory)this).Build(); var host = CreateBuilder().UseServer((IServerFactory)this).Build();
var env = application.Services.GetService<IHostingEnvironment>(); var env = host.Services.GetService<IHostingEnvironment>();
Assert.Equal(EnvironmentName.Production, env.EnvironmentName); Assert.Equal(EnvironmentName.Production, env.EnvironmentName);
} }
@ -282,7 +282,7 @@ namespace Microsoft.AspNet.Hosting
{ {
var vals = new Dictionary<string, string> var vals = new Dictionary<string, string>
{ {
// Old key is actualy ASPNET_ENV but WebApplicationConfiguration expects environment // Old key is actualy ASPNET_ENV but WebHostConfiguration expects environment
// variable names stripped from ASPNET_ prefix so using just ENV here // variable names stripped from ASPNET_ prefix so using just ENV here
{ "ENV", "Staging" } { "ENV", "Staging" }
}; };
@ -291,8 +291,8 @@ namespace Microsoft.AspNet.Hosting
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).UseServer((IServerFactory)this).Build(); var host = CreateBuilder(config).UseServer((IServerFactory)this).Build();
var env = application.Services.GetService<IHostingEnvironment>(); var env = host.Services.GetService<IHostingEnvironment>();
Assert.Equal("Staging", env.EnvironmentName); Assert.Equal("Staging", env.EnvironmentName);
} }
@ -308,8 +308,8 @@ namespace Microsoft.AspNet.Hosting
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).UseServer((IServerFactory)this).Build(); var host = CreateBuilder(config).UseServer((IServerFactory)this).Build();
var env = application.Services.GetService<IHostingEnvironment>(); var env = host.Services.GetService<IHostingEnvironment>();
Assert.Equal("Staging", env.EnvironmentName); Assert.Equal("Staging", env.EnvironmentName);
} }
@ -325,8 +325,8 @@ namespace Microsoft.AspNet.Hosting
.AddInMemoryCollection(vals); .AddInMemoryCollection(vals);
var config = builder.Build(); var config = builder.Build();
var application = CreateBuilder(config).UseServer((IServerFactory)this).Build(); var host = CreateBuilder(config).UseServer((IServerFactory)this).Build();
var env = application.Services.GetService<IHostingEnvironment>(); var env = host.Services.GetService<IHostingEnvironment>();
Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath); Assert.Equal(Path.GetFullPath("testroot"), env.WebRootPath);
Assert.True(env.WebRootFileProvider.GetFileInfo("TextFile.txt").Exists); Assert.True(env.WebRootFileProvider.GetFileInfo("TextFile.txt").Exists);
} }
@ -334,11 +334,11 @@ namespace Microsoft.AspNet.Hosting
[Fact] [Fact]
public void IsEnvironment_Extension_Is_Case_Insensitive() public void IsEnvironment_Extension_Is_Case_Insensitive()
{ {
var application = CreateBuilder().UseServer((IServerFactory)this).Build(); var host = CreateBuilder().UseServer((IServerFactory)this).Build();
using (application) using (host)
{ {
application.Start(); host.Start();
var env = application.Services.GetRequiredService<IHostingEnvironment>(); var env = host.Services.GetRequiredService<IHostingEnvironment>();
Assert.True(env.IsEnvironment(EnvironmentName.Production)); Assert.True(env.IsEnvironment(EnvironmentName.Production));
Assert.True(env.IsEnvironment("producTion")); Assert.True(env.IsEnvironment("producTion"));
} }
@ -366,7 +366,7 @@ namespace Microsoft.AspNet.Hosting
} }
[Fact] [Fact]
public void WebApplication_CreatesDefaultRequestIdentifierFeature_IfNotPresent() public void WebHost_CreatesDefaultRequestIdentifierFeature_IfNotPresent()
{ {
// Arrange // Arrange
HttpContext httpContext = null; HttpContext httpContext = null;
@ -375,10 +375,10 @@ namespace Microsoft.AspNet.Hosting
httpContext = innerHttpContext; httpContext = innerHttpContext;
return Task.FromResult(0); return Task.FromResult(0);
}); });
var application = CreateApplication(requestDelegate); var host = CreateHost(requestDelegate);
// Act // Act
application.Start(); host.Start();
// Assert // Assert
Assert.NotNull(httpContext); Assert.NotNull(httpContext);
@ -388,7 +388,7 @@ namespace Microsoft.AspNet.Hosting
} }
[Fact] [Fact]
public void WebApplication_DoesNot_CreateDefaultRequestIdentifierFeature_IfPresent() public void WebHost_DoesNot_CreateDefaultRequestIdentifierFeature_IfPresent()
{ {
// Arrange // Arrange
HttpContext httpContext = null; HttpContext httpContext = null;
@ -399,10 +399,10 @@ namespace Microsoft.AspNet.Hosting
}); });
var requestIdentifierFeature = new StubHttpRequestIdentifierFeature(); var requestIdentifierFeature = new StubHttpRequestIdentifierFeature();
_featuresSupportedByThisHost[typeof(IHttpRequestIdentifierFeature)] = requestIdentifierFeature; _featuresSupportedByThisHost[typeof(IHttpRequestIdentifierFeature)] = requestIdentifierFeature;
var application = CreateApplication(requestDelegate); var host = CreateHost(requestDelegate);
// Act // Act
application.Start(); host.Start();
// Assert // Assert
Assert.NotNull(httpContext); Assert.NotNull(httpContext);
@ -410,17 +410,17 @@ namespace Microsoft.AspNet.Hosting
} }
[Fact] [Fact]
public void WebApplication_InvokesConfigureMethodsOnlyOnce() public void WebHost_InvokesConfigureMethodsOnlyOnce()
{ {
var application = CreateBuilder() var host = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
.UseStartup<CountStartup>() .UseStartup<CountStartup>()
.Build(); .Build();
using (application) using (host)
{ {
application.Start(); host.Start();
var services = application.Services; var services = host.Services;
var services2 = application.Services; var services2 = host.Services;
Assert.Equal(1, CountStartup.ConfigureCount); Assert.Equal(1, CountStartup.ConfigureCount);
Assert.Equal(1, CountStartup.ConfigureServicesCount); Assert.Equal(1, CountStartup.ConfigureServicesCount);
} }
@ -443,7 +443,7 @@ namespace Microsoft.AspNet.Hosting
} }
[Fact] [Fact]
public void WebApplication_ThrowsForBadConfigureServiceSignature() public void WebHost_ThrowsForBadConfigureServiceSignature()
{ {
var builder = CreateBuilder() var builder = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
@ -459,7 +459,7 @@ namespace Microsoft.AspNet.Hosting
public void Configure(IApplicationBuilder app) { } public void Configure(IApplicationBuilder app) { }
} }
private IWebApplication CreateApplication(RequestDelegate requestDelegate) private IWebHost CreateHost(RequestDelegate requestDelegate)
{ {
var builder = CreateBuilder() var builder = CreateBuilder()
.UseServer((IServerFactory)this) .UseServer((IServerFactory)this)
@ -474,12 +474,12 @@ namespace Microsoft.AspNet.Hosting
private void RunMapPath(string virtualPath, string expectedSuffix) private void RunMapPath(string virtualPath, string expectedSuffix)
{ {
var application = CreateBuilder().UseServer((IServerFactory)this).Build(); var host = CreateBuilder().UseServer((IServerFactory)this).Build();
using (application) using (host)
{ {
application.Start(); host.Start();
var env = application.Services.GetRequiredService<IHostingEnvironment>(); var env = host.Services.GetRequiredService<IHostingEnvironment>();
// MapPath requires webroot to be set, we don't care // MapPath requires webroot to be set, we don't care
// about file provider so just set it here // about file provider so just set it here
env.WebRootPath = "."; env.WebRootPath = ".";
@ -489,9 +489,9 @@ namespace Microsoft.AspNet.Hosting
} }
} }
private IWebApplicationBuilder CreateBuilder(IConfiguration config = null) private IWebHostBuilder CreateBuilder(IConfiguration config = null)
{ {
return new WebApplicationBuilder().UseConfiguration(config ?? new ConfigurationBuilder().Build()).UseStartup("Microsoft.AspNet.Hosting.Tests"); return new WebHostBuilder().UseConfiguration(config ?? new ConfigurationBuilder().Build()).UseStartup("Microsoft.AspNet.Hosting.Tests");
} }
public void Start<TContext>(IHttpApplication<TContext> application) public void Start<TContext>(IHttpApplication<TContext> application)

View File

@ -283,10 +283,10 @@ namespace Microsoft.AspNet.TestHost
{ {
// This logger will attempt to access information from HttpRequest once the HttpContext is created // This logger will attempt to access information from HttpRequest once the HttpContext is created
var logger = new VerifierLogger(); var logger = new VerifierLogger();
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddSingleton<ILogger<WebApplication>>(logger); services.AddSingleton<ILogger<WebHost>>(logger);
}) })
.Configure(app => .Configure(app =>
{ {
@ -301,7 +301,7 @@ namespace Microsoft.AspNet.TestHost
var result = await server.CreateClient().GetStringAsync("/"); var result = await server.CreateClient().GetStringAsync("/");
} }
private class VerifierLogger : ILogger<WebApplication> private class VerifierLogger : ILogger<WebHost>
{ {
public IDisposable BeginScopeImpl(object state) => new NoopDispoasble(); public IDisposable BeginScopeImpl(object state) => new NoopDispoasble();

View File

@ -14,7 +14,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono)] [FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public void AddRequestHeader() public void AddRequestHeader()
{ {
var builder = new WebApplicationBuilder().Configure(app => { }); var builder = new WebHostBuilder().Configure(app => { });
var server = new TestServer(builder); var server = new TestServer(builder);
server.CreateRequest("/") server.CreateRequest("/")
.AddHeader("Host", "MyHost:90") .AddHeader("Host", "MyHost:90")
@ -27,7 +27,7 @@ namespace Microsoft.AspNet.TestHost
[Fact] [Fact]
public void AddContentHeaders() public void AddContentHeaders()
{ {
var builder = new WebApplicationBuilder().Configure(app => { }); var builder = new WebHostBuilder().Configure(app => { });
var server = new TestServer(builder); var server = new TestServer(builder);
server.CreateRequest("/") server.CreateRequest("/")
.AddHeader("Content-Type", "Test/Value") .AddHeader("Content-Type", "Test/Value")

View File

@ -30,7 +30,7 @@ namespace Microsoft.AspNet.TestHost
var expected = "GET Response"; var expected = "GET Response";
RequestDelegate appDelegate = ctx => RequestDelegate appDelegate = ctx =>
ctx.Response.WriteAsync(expected); ctx.Response.WriteAsync(expected);
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
@ -53,7 +53,7 @@ namespace Microsoft.AspNet.TestHost
Assert.Equal("/", ctx.Request.Path.Value); Assert.Equal("/", ctx.Request.Path.Value);
return ctx.Response.WriteAsync(expected); return ctx.Response.WriteAsync(expected);
}; };
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
@ -76,7 +76,7 @@ namespace Microsoft.AspNet.TestHost
Assert.Equal("/", ctx.Request.Path.Value); Assert.Equal("/", ctx.Request.Path.Value);
return ctx.Response.WriteAsync(expected); return ctx.Response.WriteAsync(expected);
}; };
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
@ -94,7 +94,7 @@ namespace Microsoft.AspNet.TestHost
// Arrange // Arrange
RequestDelegate appDelegate = ctx => RequestDelegate appDelegate = ctx =>
ctx.Response.WriteAsync(new StreamReader(ctx.Request.Body).ReadToEnd() + " PUT Response"); ctx.Response.WriteAsync(new StreamReader(ctx.Request.Body).ReadToEnd() + " PUT Response");
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
@ -113,7 +113,7 @@ namespace Microsoft.AspNet.TestHost
// Arrange // Arrange
RequestDelegate appDelegate = async ctx => RequestDelegate appDelegate = async ctx =>
await ctx.Response.WriteAsync(new StreamReader(ctx.Request.Body).ReadToEnd() + " POST Response"); await ctx.Response.WriteAsync(new StreamReader(ctx.Request.Body).ReadToEnd() + " POST Response");
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
@ -154,10 +154,10 @@ namespace Microsoft.AspNet.TestHost
} }
} }
}; };
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddSingleton<ILogger<WebApplication>>(logger); services.AddSingleton<ILogger<WebHost>>(logger);
}) })
.Configure(app => .Configure(app =>
{ {
@ -197,7 +197,7 @@ namespace Microsoft.AspNet.TestHost
} }
private class VerifierLogger : ILogger<WebApplication> private class VerifierLogger : ILogger<WebHost>
{ {
public IDisposable BeginScopeImpl(object state) => new NoopDispoasble(); public IDisposable BeginScopeImpl(object state) => new NoopDispoasble();
@ -227,7 +227,7 @@ namespace Microsoft.AspNet.TestHost
websocket.Dispose(); websocket.Dispose();
} }
}; };
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(appDelegate); app.Run(appDelegate);
}); });
@ -261,7 +261,7 @@ namespace Microsoft.AspNet.TestHost
} }
} }
}; };
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(appDelegate); app.Run(appDelegate);
}); });
@ -310,7 +310,7 @@ namespace Microsoft.AspNet.TestHost
}; };
// Act // Act
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345"); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345");
@ -342,7 +342,7 @@ namespace Microsoft.AspNet.TestHost
}; };
// Act // Act
var builder = new WebApplicationBuilder().Configure(app => app.Run(appDelegate)); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder); var server = new TestServer(builder);
var client = server.CreateClient(); var client = server.CreateClient();
var cts = new CancellationTokenSource(); var cts = new CancellationTokenSource();

View File

@ -27,14 +27,14 @@ namespace Microsoft.AspNet.TestHost
{ {
// Arrange // Arrange
// Act & Assert (Does not throw) // Act & Assert (Does not throw)
new TestServer(new WebApplicationBuilder().Configure(app => { })); new TestServer(new WebHostBuilder().Configure(app => { }));
} }
[Fact] [Fact]
public void DoesNotCaptureStartupErrorsByDefault() public void DoesNotCaptureStartupErrorsByDefault()
{ {
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.Configure(app => .Configure(app =>
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
@ -47,7 +47,7 @@ namespace Microsoft.AspNet.TestHost
[Fact] [Fact]
public void CaptureStartupErrorsSettingPreserved() public void CaptureStartupErrorsSettingPreserved()
{ {
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.UseCaptureStartupErrors(true) .UseCaptureStartupErrors(true)
.Configure(app => .Configure(app =>
{ {
@ -62,7 +62,7 @@ namespace Microsoft.AspNet.TestHost
public void ApplicationServicesAvailableFromTestServer() public void ApplicationServicesAvailableFromTestServer()
{ {
var testService = new TestService(); var testService = new TestService();
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.Configure(app => { }) .Configure(app => { })
.ConfigureServices(services => .ConfigureServices(services =>
{ {
@ -70,14 +70,14 @@ namespace Microsoft.AspNet.TestHost
}); });
var server = new TestServer(builder); var server = new TestServer(builder);
Assert.Equal(testService, server.Application.Services.GetRequiredService<TestService>()); Assert.Equal(testService, server.Host.Services.GetRequiredService<TestService>());
} }
[ConditionalFact] [ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task RequestServicesAutoCreated() public async Task RequestServicesAutoCreated()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -114,7 +114,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CustomServiceProviderSetsApplicationServices() public async Task CustomServiceProviderSetsApplicationServices()
{ {
var builder = new WebApplicationBuilder().UseStartup<CustomContainerStartup>(); var builder = new WebHostBuilder().UseStartup<CustomContainerStartup>();
var server = new TestServer(builder); var server = new TestServer(builder);
string result = await server.CreateClient().GetStringAsync("/path"); string result = await server.CreateClient().GetStringAsync("/path");
Assert.Equal("ApplicationServicesEqual:True", result); Assert.Equal("ApplicationServicesEqual:True", result);
@ -157,7 +157,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task ExistingRequestServicesWillNotBeReplaced() public async Task ExistingRequestServicesWillNotBeReplaced()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -179,7 +179,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanSetCustomServiceProvider() public async Task CanSetCustomServiceProvider()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -229,7 +229,7 @@ namespace Microsoft.AspNet.TestHost
public async Task ExistingServiceProviderFeatureWillNotBeReplaced() public async Task ExistingServiceProviderFeatureWillNotBeReplaced()
{ {
var appServices = new ServiceCollection().BuildServiceProvider(); var appServices = new ServiceCollection().BuildServiceProvider();
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -271,7 +271,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task WillReplaceServiceProviderFeatureWithNullRequestServices() public async Task WillReplaceServiceProviderFeatureWithNullRequestServices()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -293,7 +293,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanAccessLogger() public async Task CanAccessLogger()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -311,7 +311,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanAccessHttpContext() public async Task CanAccessHttpContext()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -343,7 +343,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanAddNewHostServices() public async Task CanAddNewHostServices()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -366,7 +366,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CreateInvokesApp() public async Task CreateInvokesApp()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(context => app.Run(context =>
{ {
@ -383,7 +383,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task DisposeStreamIgnored() public async Task DisposeStreamIgnored()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
{ {
@ -402,7 +402,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task DisposedServerThrows() public async Task DisposedServerThrows()
{ {
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
app.Run(async context => app.Run(async context =>
{ {
@ -422,7 +422,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CancelAborts() public async Task CancelAborts()
{ {
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.Configure(app => .Configure(app =>
{ {
app.Run(context => app.Run(context =>
@ -441,7 +441,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanCreateViaStartupType() public async Task CanCreateViaStartupType()
{ {
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.UseStartup<TestStartup>(); .UseStartup<TestStartup>();
var server = new TestServer(builder); var server = new TestServer(builder);
HttpResponseMessage result = await server.CreateClient().GetAsync("/"); HttpResponseMessage result = await server.CreateClient().GetAsync("/");
@ -453,7 +453,7 @@ namespace Microsoft.AspNet.TestHost
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Hangs randomly (issue #507)")]
public async Task CanCreateViaStartupTypeAndSpecifyEnv() public async Task CanCreateViaStartupTypeAndSpecifyEnv()
{ {
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.UseStartup<TestStartup>() .UseStartup<TestStartup>()
.UseEnvironment("Foo"); .UseEnvironment("Foo");
var server = new TestServer(builder); var server = new TestServer(builder);
@ -469,7 +469,7 @@ namespace Microsoft.AspNet.TestHost
{ {
DiagnosticListener diagnosticListener = null; DiagnosticListener diagnosticListener = null;
var builder = new WebApplicationBuilder() var builder = new WebHostBuilder()
.Configure(app => .Configure(app =>
{ {
diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>(); diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
@ -498,7 +498,7 @@ namespace Microsoft.AspNet.TestHost
public async Task ExceptionDiagnosticAvailable() public async Task ExceptionDiagnosticAvailable()
{ {
DiagnosticListener diagnosticListener = null; DiagnosticListener diagnosticListener = null;
var builder = new WebApplicationBuilder().Configure(app => var builder = new WebHostBuilder().Configure(app =>
{ {
diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>(); diagnosticListener = app.ApplicationServices.GetRequiredService<DiagnosticListener>();
app.Run(context => app.Run(context =>