Cleanup and add test for CreateDefaultBuilderOfT

This commit is contained in:
John Luo 2017-09-28 15:58:14 -07:00
parent 07bf8d02a0
commit 7ec8cc5fad
10 changed files with 141 additions and 50 deletions

View File

@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26510.0
VisualStudioVersion = 15.0.26923.0
MinimumVisualStudioVersion = 15.0.26730.03
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{ED834E68-51C3-4ADE-ACC8-6BA6D4207C09}"
ProjectSection(SolutionItems) = preProject
@ -50,6 +50,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TrimDeps", "tools\TrimDeps\
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DependencyInjectionApp", "test\TestSites\DependencyInjectionApp\DependencyInjectionApp.csproj", "{65FE2E38-4529-4C93-A7B0-CF12DD7A70C3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreateDefaultBuilderOfTApp", "test\TestSites\CreateDefaultBuilderOfTApp\CreateDefaultBuilderOfTApp.csproj", "{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -96,6 +98,10 @@ Global
{65FE2E38-4529-4C93-A7B0-CF12DD7A70C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{65FE2E38-4529-4C93-A7B0-CF12DD7A70C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{65FE2E38-4529-4C93-A7B0-CF12DD7A70C3}.Release|Any CPU.Build.0 = Release|Any CPU
{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -113,5 +119,9 @@ Global
{79CF58CE-B020-45D8-BDB5-2D8036BEAD14} = {EC22261D-0DE1-47DE-8F7C-072675D6F5B4}
{67E4C92F-6D12-4C52-BB79-B8D11BFC6B82} = {ED834E68-51C3-4ADE-ACC8-6BA6D4207C09}
{65FE2E38-4529-4C93-A7B0-CF12DD7A70C3} = {EC22261D-0DE1-47DE-8F7C-072675D6F5B4}
{A922B5AC-836B-44F4-83F1-3CB9EB08A3F8} = {EC22261D-0DE1-47DE-8F7C-072675D6F5B4}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A666E9B0-125B-4975-B35B-09A6D68A5047}
EndGlobalSection
EndGlobal

View File

@ -189,10 +189,8 @@ namespace Microsoft.AspNetCore
}
/// <summary>
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults using typed Startup
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults using typed Startup.
/// </summary>
/// <typeparam name="T">Specify the startup type to be used by the web host.</typeparam>
/// <param name="args">The command line args.</param>
/// <remarks>
/// The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
/// use Kestrel as the web server,
@ -200,27 +198,18 @@ namespace Microsoft.AspNetCore
/// load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
/// load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
/// load <see cref="IConfiguration"/> from environment variables,
/// load <see cref="IConfiguration"/> from supplied command line args,
/// configures the <see cref="ILoggerFactory"/> to log to the console and debug output,
/// enables IIS integration,
/// enables the ability for frameworks to bind their options to their default configuration sections,
/// adds the developer exception page when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development'
/// and sets the startup class as the typed defined in T.
/// enables the ability for frameworks to bind their options to their default configuration sections.
/// </remarks>
/// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam>
/// <param name="args">The command line args.</param>
/// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder CreateDefaultBuilder<T>(string[] args) where T : class
public static IWebHostBuilder CreateDefaultBuilder<TStartup>(string[] args) where TStartup : class
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<T>();
}
/// <summary>
/// Builds an Microsoft.AspNetCore.Hosting.IWebHost which hosts a web application and
/// runs a web application and block the calling thread until host shutdown.
/// </summary>
/// <param name="builder">The <see cref="IWebHostBuilder"/></param>
public static void BuildAndRun(this IWebHostBuilder builder)
{
builder.Build().Run();
return CreateDefaultBuilder(args)
.UseStartup<TStartup>();
}
}
}

View File

@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
@ -73,6 +72,32 @@ namespace Microsoft.AspNetCore.Tests
}, setTestEnvVars: true);
}
[Fact]
public async Task CreateDefaultBuilderOfT_InitializeWithDefaults()
{
var applicationName = "CreateDefaultBuilderOfTApp";
await ExecuteTestApp(applicationName, async (deploymentResult, logger) =>
{
var response = await RetryHelper.RetryRequest(() => deploymentResult.HttpClient.GetAsync(string.Empty), logger, deploymentResult.HostShutdownToken);
var responseText = await response.Content.ReadAsStringAsync();
try
{
// Assert server is Kestrel
Assert.Equal("Kestrel", response.Headers.Server.ToString());
// The application name will be sent in response when all asserts succeed in the test app.
Assert.Equal(applicationName, responseText);
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
logger.LogWarning(responseText);
throw;
}
}, setTestEnvVars: true);
}
[Theory]
[InlineData("Development", "InvalidOperationException: Cannot consume scoped service")]
[InlineData("Production", "Success")]

View File

@ -2,18 +2,12 @@
// 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 System.IO;
using System.Linq;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
namespace CreateDefaultBuilderApp
{
@ -36,11 +30,6 @@ namespace CreateDefaultBuilderApp
});
})
.Build().Run();
Console.ReadKey();
WebHost.CreateDefaultBuilder<Startup>(new[] { "--cliKey", "cliValue" })
.BuildAndRun();
}
private static string GetResponseMessage(WebHostBuilderContext context, IServiceCollection services)

View File

@ -1,18 +0,0 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace CreateDefaultBuilderApp
{
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<UserSecretsId>aspnetcore-CreateDefaultBuilderOfT-20170424224131</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Microsoft.AspNetCore\Microsoft.AspNetCore.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,14 @@
// 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 Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace CreateDefaultBuilderOfTApp
{
public class Program
{
static void Main(string[] args) => WebHost.CreateDefaultBuilder<Startup>(new[] { "--cliKey", "cliValue" }) .Build().Run();
}
}

View File

@ -0,0 +1,63 @@
// 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.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace CreateDefaultBuilderOfTApp
{
class Startup
{
public void Configure(IApplicationBuilder app, WebHostBuilderContext webHostBuilderContext)
{
app.Run(context =>
{
return context.Response.WriteAsync(GetResponseMessage(webHostBuilderContext));
});
}
private static string GetResponseMessage(WebHostBuilderContext context)
{
// Verify ContentRootPath set
if (!string.Equals(Directory.GetCurrentDirectory(), context.HostingEnvironment.ContentRootPath, StringComparison.Ordinal))
{
return $"Current directory incorrect. Expected: {Directory.GetCurrentDirectory()} Actual: {context.HostingEnvironment.ContentRootPath}";
}
// Verify appsettings.json loaded
if (!string.Equals("settingsValue", context.Configuration["settingsKey"], StringComparison.Ordinal))
{
return $"appsettings.json not loaded into Configuration.";
}
// Verify appsettings.environment.json loaded
if (!string.Equals("devSettingsValue", context.Configuration["devSettingsKey"], StringComparison.Ordinal))
{
return $"appsettings.{context.HostingEnvironment.EnvironmentName}.json not loaded into Configuration.";
}
// TODO: Verify UserSecrets loaded
// Verify environment variables loaded
if (!string.Equals("envValue", context.Configuration["envKey"], StringComparison.Ordinal))
{
return $"Environment variables not loaded into Configuration.";
}
// Verify command line arguments loaded
if (!string.Equals("cliValue", context.Configuration["cliKey"], StringComparison.Ordinal))
{
return $"Command line arguments not loaded into Configuration.";
}
// TODO: Verify AddConsole called
// TODO: Verify AddDebug called
// TODO: Verify UseIISIntegration called
return context.HostingEnvironment.ApplicationName;
}
}
}

View File

@ -0,0 +1,3 @@
{
"devSettingsKey": "devSettingsValue"
}

View File

@ -0,0 +1,3 @@
{
"settingsKey": "settingsValue"
}