// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Builder.Internal { public class ApplicationBuilder : IApplicationBuilder { private readonly IList> _components = new List>(); public ApplicationBuilder(IServiceProvider serviceProvider) { Properties = new Dictionary(); ApplicationServices = serviceProvider; } public ApplicationBuilder(IServiceProvider serviceProvider, object server) : this(serviceProvider) { SetProperty(Constants.BuilderProperties.ServerFeatures, server); } private ApplicationBuilder(ApplicationBuilder builder) { Properties = builder.Properties; } public IServiceProvider ApplicationServices { get { return GetProperty(Constants.BuilderProperties.ApplicationServices); } set { SetProperty(Constants.BuilderProperties.ApplicationServices, value); } } public IFeatureCollection ServerFeatures { get { return GetProperty(Constants.BuilderProperties.ServerFeatures); } } public IDictionary Properties { get; } private T GetProperty(string key) { object value; return Properties.TryGetValue(key, out value) ? (T)value : default(T); } private void SetProperty(string key, T value) { Properties[key] = value; } public IApplicationBuilder Use(Func middleware) { _components.Add(middleware); return this; } public IApplicationBuilder New() { return new ApplicationBuilder(this); } public RequestDelegate Build() { RequestDelegate app = context => { context.Response.StatusCode = 404; return TaskCache.CompletedTask; }; foreach (var component in _components.Reverse()) { app = component(app); } return app; } } }