Block generic host Startup.ConfigureServices that return IServiceProvider #5149 (#6997)

This commit is contained in:
Chris Ross 2019-01-25 08:16:39 -08:00 committed by GitHub
parent aef117ff3f
commit a16a6dfaeb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 3 deletions

View File

@ -232,6 +232,10 @@ namespace Microsoft.AspNetCore.Hosting.Internal
{
throw new NotSupportedException($"{typeof(IStartup)} isn't supported");
}
if (StartupLoader.HasConfigureServicesIServiceProviderDelegate(startupType, context.HostingEnvironment.EnvironmentName))
{
throw new NotSupportedException($"ConfigureServices returning an {typeof(IServiceProvider)} isn't supported.");
}
instance = ActivatorUtilities.CreateInstance(new HostServiceProvider(webHostBuilderContext), startupType);
context.Properties[_startupKey] = instance;

View File

@ -279,6 +279,11 @@ namespace Microsoft.AspNetCore.Hosting.Internal
return new ConfigureContainerBuilder(configureMethod);
}
internal static bool HasConfigureServicesIServiceProviderDelegate(Type startupType, string environmentName)
{
return null != FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false);
}
internal static ConfigureServicesBuilder FindConfigureServicesDelegate(Type startupType, string environmentName)
{
var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false)
@ -333,4 +338,4 @@ namespace Microsoft.AspNetCore.Hosting.Internal
return methodInfo;
}
}
}
}

View File

@ -4,7 +4,7 @@ using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Hosting.Fakes
{
public class StartupWithNullConfigureServices
public class StartupWithBuiltConfigureServices
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
@ -13,4 +13,4 @@ namespace Microsoft.AspNetCore.Hosting.Fakes
public void Configure(IApplicationBuilder app) { }
}
}
}

View File

@ -889,6 +889,22 @@ namespace Microsoft.AspNetCore.Hosting
Assert.Equal("Building this implementation of IWebHostBuilder is not supported.", exception.Message);
}
[Fact]
public void GenericWebHostDoesNotSupportBuildingInConfigureServices()
{
var hostBuilder = new HostBuilder()
.ConfigureWebHost(builder =>
{
builder.UseStartup<StartupWithBuiltConfigureServices>();
});
var exception = Assert.Throws<NotSupportedException>(() =>
{
hostBuilder.Build();
});
Assert.Equal($"ConfigureServices returning an {typeof(IServiceProvider)} isn't supported.", exception.Message);
}
[Theory]
[MemberData(nameof(DefaultWebHostBuildersWithConfig))]
public void Build_HostingStartupAssemblyCanBeExcluded(IWebHostBuilder builder)