Move service registration before hosting startups run (#10105)

* Move service registration before hosting startups run
- This allows IHostingStartup to see default service registrations and override them.
- Added a test to verify that hosting startup can see the IWebHostingEnvironment. Unfortunately this is used by MVC to get the application name before the container is baked. This was found when porting our workshop from 2.2 to 3.0
This commit is contained in:
David Fowler 2019-05-09 09:14:31 -07:00 committed by GitHub
parent a677fd231e
commit dcf49f2575
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 9 deletions

View File

@ -55,15 +55,6 @@ namespace Microsoft.AspNetCore.Hosting.Internal
}
});
_builder.ConfigureServices((context, services) =>
{
if (_hostingStartupWebHostBuilder != null)
{
var webhostContext = GetWebHostBuilderContext(context);
_hostingStartupWebHostBuilder.ConfigureServices(webhostContext, services);
}
});
_builder.ConfigureServices((context, services) =>
{
var webhostContext = GetWebHostBuilderContext(context);
@ -96,6 +87,9 @@ namespace Microsoft.AspNetCore.Hosting.Internal
services.TryAddScoped<IMiddlewareFactory, MiddlewareFactory>();
services.TryAddSingleton<IApplicationBuilderFactory, ApplicationBuilderFactory>();
// IMPORTANT: This needs to run *before* direct calls on the builder (like UseStartup)
_hostingStartupWebHostBuilder?.ConfigureServices(webhostContext, services);
// Support UseStartup(assemblyName)
if (!string.IsNullOrEmpty(webHostOptions.StartupAssembly))
{

View File

@ -1472,6 +1472,19 @@ namespace Microsoft.AspNetCore.Hosting
var loggerProvider = new TestLoggerProvider();
builder.UseSetting("testhostingstartup", "0")
.UseSetting("testhostingstartup_chain", builder.GetSetting("testhostingstartup_chain") + "0")
.ConfigureServices(services =>
{
// This check is required because MVC still uses the
// IWebHostEnvironment instance before the container is baked
#pragma warning disable CS0618 // Type or member is obsolete
var heDescriptor = services.SingleOrDefault(s => s.ServiceType == typeof(IHostingEnvironment));
Assert.NotNull(heDescriptor);
Assert.NotNull(heDescriptor.ImplementationInstance);
#pragma warning restore CS0618 // Type or member is obsolete
var wheDescriptor = services.SingleOrDefault(s => s.ServiceType == typeof(IWebHostEnvironment));
Assert.NotNull(wheDescriptor);
Assert.NotNull(wheDescriptor.ImplementationInstance);
})
.ConfigureServices(services => services.AddSingleton<ServiceA>())
.ConfigureServices(services => services.AddSingleton<ITestSink>(loggerProvider.Sink))
.ConfigureLogging((_, lf) => lf.AddProvider(loggerProvider))