From 1354d66fb6dbaa732e18c66daf40a6fda20b7b90 Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Mon, 11 May 2015 15:08:40 -0700 Subject: [PATCH] Ensure ConfigureServices is only called once --- .../Internal/HostingEngine.cs | 11 ++++--- .../HostingEngineTests.cs | 32 +++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.AspNet.Hosting/Internal/HostingEngine.cs b/src/Microsoft.AspNet.Hosting/Internal/HostingEngine.cs index 48a0069b92..924d336e1d 100644 --- a/src/Microsoft.AspNet.Hosting/Internal/HostingEngine.cs +++ b/src/Microsoft.AspNet.Hosting/Internal/HostingEngine.cs @@ -91,11 +91,12 @@ namespace Microsoft.AspNet.Hosting.Internal private void EnsureApplicationServices() { - EnsureStartup(); - - _applicationServiceCollection.AddInstance(_applicationLifetime); - - _applicationServices = Startup.ConfigureServicesDelegate(_applicationServiceCollection); + if (_applicationServices == null) + { + EnsureStartup(); + _applicationServiceCollection.AddInstance(_applicationLifetime); + _applicationServices = Startup.ConfigureServicesDelegate(_applicationServiceCollection); + } } private void EnsureStartup() diff --git a/test/Microsoft.AspNet.Hosting.Tests/HostingEngineTests.cs b/test/Microsoft.AspNet.Hosting.Tests/HostingEngineTests.cs index 6c613adcf7..6ad8ab0b87 100644 --- a/test/Microsoft.AspNet.Hosting.Tests/HostingEngineTests.cs +++ b/test/Microsoft.AspNet.Hosting.Tests/HostingEngineTests.cs @@ -291,6 +291,38 @@ namespace Microsoft.AspNet.Hosting Assert.Same(requestIdentifierFeature, httpContext.GetFeature()); } + [Fact] + public void HostingEngine_InvokesConfigureMethodsOnlyOnce() + { + var engine = CreateBuilder() + .UseServer(this) + .UseStartup() + .Build(); + using (engine.Start()) + { + var services = engine.ApplicationServices; + var services2 = engine.ApplicationServices; + Assert.Equal(1, CountStartup.ConfigureCount); + Assert.Equal(1, CountStartup.ConfigureServicesCount); + } + } + + public class CountStartup + { + public static int ConfigureServicesCount; + public static int ConfigureCount; + + public void ConfigureServices(IServiceCollection services) + { + ConfigureServicesCount++; + } + + public void Configure(IApplicationBuilder app) + { + ConfigureCount++; + } + } + private IHostingEngine CreateHostingEngine(RequestDelegate requestDelegate) { var applicationBuilder = new Mock();