Skip to content

Commit 673a664

Browse files
authored
set scope and build validation in dev when no options provided (#99199)
1 parent a008f7c commit 673a664

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,15 @@ public partial class HostBuilder : IHostBuilder
3737
private HostingEnvironment? _hostingEnvironment;
3838
private IServiceProvider? _appServices;
3939
private PhysicalFileProvider? _defaultProvider;
40+
private readonly bool _defaultProviderFactoryUsed;
4041

4142
/// <summary>
4243
/// Initializes a new instance of <see cref="HostBuilder"/>.
4344
/// </summary>
4445
public HostBuilder()
4546
{
4647
_serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory());
48+
_defaultProviderFactoryUsed = true;
4749
}
4850

4951
/// <summary>
@@ -344,6 +346,11 @@ private void InitializeServiceProvider()
344346
configureServicesAction(_hostBuilderContext!, services);
345347
}
346348

349+
if (_hostBuilderContext!.HostingEnvironment.IsDevelopment() && _defaultProviderFactoryUsed)
350+
{
351+
_serviceProviderFactory = new ServiceFactoryAdapter<IServiceCollection>(new DefaultServiceProviderFactory(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }));
352+
}
353+
347354
object containerBuilder = _serviceProviderFactory.CreateBuilder(services);
348355

349356
foreach (IConfigureContainerAdapter containerAction in _configureContainerActions)

src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/HostBuilderTests.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,33 @@ public void CustomContainerTypeMismatchThrows()
533533
Assert.Throws<InvalidCastException>(() => hostBuilder.Build());
534534
}
535535

536+
[Fact]
537+
public void ScopeValidationEnabledInDevelopment()
538+
{
539+
using var host = new HostBuilder()
540+
.UseEnvironment(Environments.Development)
541+
.ConfigureServices(serices =>
542+
{
543+
serices.AddScoped<ServiceA>();
544+
})
545+
.Build();
546+
547+
Assert.Throws<InvalidOperationException>(() => { host.Services.GetRequiredService<ServiceA>(); });
548+
}
549+
550+
[Fact]
551+
public void ValidateOnBuildEnabledInDevelopment()
552+
{
553+
var hostBuilder = new HostBuilder()
554+
.UseEnvironment(Environments.Development)
555+
.ConfigureServices(serices =>
556+
{
557+
serices.AddSingleton<ServiceC>();
558+
});
559+
560+
Assert.Throws<AggregateException>(() => hostBuilder.Build());
561+
}
562+
536563
[Fact]
537564
public void HostingContextContainsAppConfigurationDuringConfigureLogging()
538565
{

0 commit comments

Comments
 (0)