Skip to content

Commit 0bb0a25

Browse files
committed
Handle tests clearing app config sources
1 parent c524ad2 commit 0bb0a25

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/DefaultBuilder/src/WebApplicationBuilder.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System.Diagnostics;
5+
using System.Linq;
56
using Microsoft.AspNetCore.Hosting;
67
using Microsoft.Extensions.Configuration;
78
using Microsoft.Extensions.DependencyInjection;
@@ -193,9 +194,19 @@ public WebApplication Build()
193194
// to the new one. This allows code that has references to the service collection to still function.
194195
_services.InnerCollection = services;
195196

197+
var hostBuilderProviders = ((IConfigurationRoot)context.Configuration).Providers;
198+
199+
if (!hostBuilderProviders.Contains(chainedConfigSource.BuiltProvider))
200+
{
201+
// Something removed the TrackingChainedConfigurationSource pointing back to the ConfigurationManager.
202+
// This is likely a test using WebApplicationFactory<TEntryPoint>.
203+
// We replicate the effect by clearing the ConfingurationManager sources.
204+
((IConfigurationBuilder)Configuration).Sources.Clear();
205+
}
206+
196207
// Make builder.Configuration match the final configuration. To do that, we add the additional
197208
// providers in the inner _hostBuilders's Configuration to the ConfigurationManager.
198-
foreach (var provider in ((IConfigurationRoot)context.Configuration).Providers)
209+
foreach (var provider in hostBuilderProviders)
199210
{
200211
if (!ReferenceEquals(provider, chainedConfigSource.BuiltProvider))
201212
{

0 commit comments

Comments
 (0)