This repository was archived by the owner on Dec 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathWebHost.cs
255 lines (217 loc) · 8.84 KB
/
WebHost.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Hosting.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Hosting.Startup;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Hosting.Internal
{
public class WebHost : IWebHost
{
private readonly IServiceCollection _applicationServiceCollection;
private readonly IStartupLoader _startupLoader;
private readonly ApplicationLifetime _applicationLifetime;
private readonly WebHostOptions _options;
private readonly IConfiguration _config;
private IServiceProvider _applicationServices;
private RequestDelegate _application;
private ILogger<WebHost> _logger;
// Used for testing only
internal WebHostOptions Options => _options;
// Only one of these should be set
internal string StartupAssemblyName { get; set; }
internal StartupMethods Startup { get; set; }
internal Type StartupType { get; set; }
private IServer Server { get; set; }
public WebHost(
IServiceCollection appServices,
IStartupLoader startupLoader,
WebHostOptions options,
IConfiguration config)
{
if (appServices == null)
{
throw new ArgumentNullException(nameof(appServices));
}
if (startupLoader == null)
{
throw new ArgumentNullException(nameof(startupLoader));
}
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
_config = config;
_options = options;
_applicationServiceCollection = appServices;
_startupLoader = startupLoader;
_applicationLifetime = new ApplicationLifetime();
_applicationServiceCollection.AddSingleton<IApplicationLifetime>(_applicationLifetime);
}
public IServiceProvider Services
{
get
{
EnsureApplicationServices();
return _applicationServices;
}
}
public IFeatureCollection ServerFeatures
{
get
{
return Server?.Features;
}
}
public void Initialize()
{
if (_application == null)
{
_application = BuildApplication();
}
}
public virtual void Start()
{
Initialize();
_logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
var diagnosticSource = _applicationServices.GetRequiredService<DiagnosticSource>();
var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>();
_logger.Starting();
Server.Start(new HostingApplication(_application, _logger, diagnosticSource, httpContextFactory));
_applicationLifetime.NotifyStarted();
_logger.Started();
}
private void EnsureApplicationServices()
{
if (_applicationServices == null)
{
EnsureStartup();
_applicationServices = Startup.ConfigureServicesDelegate(_applicationServiceCollection);
}
}
private void EnsureStartup()
{
if (Startup != null)
{
return;
}
if (StartupType == null)
{
var diagnosticTypeMessages = new List<string>();
StartupType = _startupLoader.FindStartupType(StartupAssemblyName, diagnosticTypeMessages);
if (StartupType == null)
{
throw new ArgumentException(
diagnosticTypeMessages.Aggregate("Failed to find a startup type for the web application.", (a, b) => a + "\r\n" + b),
StartupAssemblyName);
}
}
var diagnosticMessages = new List<string>();
Startup = _startupLoader.LoadMethods(StartupType, diagnosticMessages);
if (Startup == null)
{
throw new ArgumentException(
diagnosticMessages.Aggregate("Failed to find a startup entry point for the web application.", (a, b) => a + "\r\n" + b),
StartupAssemblyName);
}
}
private RequestDelegate BuildApplication()
{
try
{
EnsureApplicationServices();
EnsureServer();
var builderFactory = _applicationServices.GetRequiredService<IApplicationBuilderFactory>();
var builder = builderFactory.CreateBuilder(Server.Features);
builder.ApplicationServices = _applicationServices;
var startupFilters = _applicationServices.GetService<IEnumerable<IStartupFilter>>();
var configure = Startup.ConfigureDelegate;
foreach (var filter in startupFilters.Reverse())
{
configure = filter.Configure(configure);
}
configure(builder);
return builder.Build();
}
catch (Exception ex) when (_options.CaptureStartupErrors)
{
// EnsureApplicationServices may have failed due to a missing or throwing Startup class.
if (_applicationServices == null)
{
_applicationServices = _applicationServiceCollection.BuildServiceProvider();
}
EnsureServer();
// Write errors to standard out so they can be retrieved when not in development mode.
Console.Out.WriteLine("Application startup exception: " + ex.ToString());
var logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
logger.ApplicationError(ex);
// Generate an HTML error page.
var hostingEnv = _applicationServices.GetRequiredService<IHostingEnvironment>();
var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors;
var errorBytes = StartupExceptionPage.GenerateErrorHtml(showDetailedErrors, ex);
return context =>
{
context.Response.StatusCode = 500;
context.Response.Headers["Cache-Control"] = "private, max-age=0";
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.ContentLength = errorBytes.Length;
return context.Response.Body.WriteAsync(errorBytes, 0, errorBytes.Length);
};
}
}
private void EnsureServer()
{
if (Server == null)
{
Server = _applicationServices.GetRequiredService<IServer>();
var addresses = Server.Features?.Get<IServerAddressesFeature>()?.Addresses;
if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0)
{
var urls = _config[WebHostDefaults.ServerUrlsKey];
if (!string.IsNullOrEmpty(urls))
{
foreach (var value in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
addresses.Add(value);
}
}
if (addresses.Count == 0)
{
// Provide a default address if there aren't any configured.
addresses.Add("http://localhost:5000");
}
}
}
}
public void Dispose()
{
_logger?.Shutdown();
_applicationLifetime.StopApplication();
Server?.Dispose();
(_applicationServices as IDisposable)?.Dispose();
_applicationLifetime.NotifyStopped();
}
private class Disposable : IDisposable
{
private Action _dispose;
public Disposable(Action dispose)
{
_dispose = dispose;
}
public void Dispose()
{
Interlocked.Exchange(ref _dispose, () => { }).Invoke();
}
}
}
}