Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,15 @@ public partial class HostBuilder : IHostBuilder
private HostingEnvironment? _hostingEnvironment;
private IServiceProvider? _appServices;
private PhysicalFileProvider? _defaultProvider;
private readonly bool _defaultProviderFactoryUsed;

/// <summary>
/// Initializes a new instance of <see cref="HostBuilder"/>.
/// </summary>
public HostBuilder()
{
_serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory());
_defaultProviderFactoryUsed = true;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this ever set to false? Should that be done in UseServiceProviderFactory?

Copy link
Contributor Author

@wcsanders1 wcsanders1 Jul 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it seems to me that this field should be set to false when UseServiceProviderFactory is called. This was my oversight I believe.

}

/// <summary>
Expand Down Expand Up @@ -349,6 +351,11 @@ private void InitializeServiceProvider()
configureServicesAction(_hostBuilderContext!, services);
}

if (_hostBuilderContext!.HostingEnvironment.IsDevelopment() && _defaultProviderFactoryUsed)
{
_serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }));
}

object containerBuilder = _serviceProviderFactory.CreateBuilder(services);

foreach (IConfigureContainerAdapter containerAction in _configureContainerActions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,33 @@ public void CustomContainerTypeMismatchThrows()
Assert.Throws<InvalidCastException>(() => hostBuilder.Build());
}

[Fact]
public void ScopeValidationEnabledInDevelopment()
{
using var host = new HostBuilder()
.UseEnvironment(Environments.Development)
.ConfigureServices(serices =>
{
serices.AddScoped<ServiceA>();
})
.Build();

Assert.Throws<InvalidOperationException>(() => { host.Services.GetRequiredService<ServiceA>(); });
}

[Fact]
public void ValidateOnBuildEnabledInDevelopment()
{
var hostBuilder = new HostBuilder()
.UseEnvironment(Environments.Development)
.ConfigureServices(serices =>
{
serices.AddSingleton<ServiceC>();
});

Assert.Throws<AggregateException>(() => hostBuilder.Build());
}

[Fact]
public void HostingContextContainsAppConfigurationDuringConfigureLogging()
{
Expand Down