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 303
Expand file tree
/
Copy pathWebHostBuilder.cs
More file actions
280 lines (238 loc) · 10.8 KB
/
WebHostBuilder.cs
File metadata and controls
280 lines (238 loc) · 10.8 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// 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.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Builder;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Startup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNetCore.Hosting
{
/// <summary>
/// A builder for <see cref="IWebHost"/>
/// </summary>
public class WebHostBuilder : IWebHostBuilder
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly List<Action<IServiceCollection>> _configureServicesDelegates;
private readonly List<Action<ILoggerFactory>> _configureLoggingDelegates;
private IConfiguration _config = new ConfigurationBuilder().AddInMemoryCollection().Build();
private ILoggerFactory _loggerFactory;
private WebHostOptions _options;
// Only one of these should be set
private StartupMethods _startup;
private Type _startupType;
/// <summary>
/// Initializes a new instance of the <see cref="WebHostBuilder"/> class.
/// </summary>
public WebHostBuilder()
{
_hostingEnvironment = new HostingEnvironment();
_configureServicesDelegates = new List<Action<IServiceCollection>>();
_configureLoggingDelegates = new List<Action<ILoggerFactory>>();
// This may end up storing null, but that's indistinguishable from not adding it.
UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
// Legacy keys, never remove these.
?? Environment.GetEnvironmentVariable("Hosting:Environment")
?? Environment.GetEnvironmentVariable("ASPNET_ENV"));
if (Environment.GetEnvironmentVariable("Hosting:Environment") != null)
{
Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null)
{
Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
}
}
/// <summary>
/// Add or replace a setting in the configuration.
/// </summary>
/// <param name="key">The key of the setting to add or replace.</param>
/// <param name="value">The value of the setting to add or replace.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseSetting(string key, string value)
{
_config[key] = value;
return this;
}
/// <summary>
/// Get the setting value from the configuration.
/// </summary>
/// <param name="key">The key of the setting to look up.</param>
/// <returns>The value the setting currently contains.</returns>
public string GetSetting(string key)
{
return _config[key];
}
/// <summary>
/// Specify the <see cref="ILoggerFactory"/> to be used by the web host.
/// </summary>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseLoggerFactory(ILoggerFactory loggerFactory)
{
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_loggerFactory = loggerFactory;
return this;
}
/// <summary>
/// Specify the startup type to be used by the web host.
/// </summary>
/// <param name="startupType">The <see cref="Type"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder UseStartup(Type startupType)
{
if (startupType == null)
{
throw new ArgumentNullException(nameof(startupType));
}
_startupType = startupType;
return this;
}
/// <summary>
/// Adds a delegate for configuring additional services for the host or web application. This may be called
/// multiple times.
/// </summary>
/// <param name="configureServices">A delegate for configuring the <see cref="IServiceCollection"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices)
{
if (configureServices == null)
{
throw new ArgumentNullException(nameof(configureServices));
}
_configureServicesDelegates.Add(configureServices);
return this;
}
/// <summary>
/// Specify the startup method to be used to configure the web application.
/// </summary>
/// <param name="configureApp">The delegate that configures the <see cref="IApplicationBuilder"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder Configure(Action<IApplicationBuilder> configureApp)
{
if (configureApp == null)
{
throw new ArgumentNullException(nameof(configureApp));
}
_startup = new StartupMethods(configureApp);
return this;
}
/// <summary>
/// Adds a delegate for configuring the provided <see cref="ILoggerFactory"/>. This may be called multiple times.
/// </summary>
/// <param name="configureLogging">The delegate that configures the <see cref="ILoggerFactory"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public IWebHostBuilder ConfigureLogging(Action<ILoggerFactory> configureLogging)
{
if (configureLogging == null)
{
throw new ArgumentNullException(nameof(configureLogging));
}
_configureLoggingDelegates.Add(configureLogging);
return this;
}
/// <summary>
/// Builds the required services and an <see cref="IWebHost"/> which hosts a web application.
/// </summary>
public IWebHost Build()
{
var hostingServices = BuildHostingServices();
var hostingContainer = hostingServices.BuildServiceProvider();
var startupLoader = hostingContainer.GetRequiredService<IStartupLoader>();
var host = new WebHost(hostingServices, startupLoader, _options, _config);
// Only one of these should be set, but they are used in priority
host.Startup = _startup;
host.StartupType = _startupType;
host.StartupAssemblyName = _options.Application;
host.Initialize();
return host;
}
private IServiceCollection BuildHostingServices()
{
_options = new WebHostOptions(_config);
var appEnvironment = PlatformServices.Default.Application;
var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, appEnvironment.ApplicationBasePath);
var applicationName = ResolveApplicationName() ?? appEnvironment.ApplicationName;
// Initialize the hosting environment
_hostingEnvironment.Initialize(applicationName, contentRootPath, _options);
var services = new ServiceCollection();
services.AddSingleton(_hostingEnvironment);
if (_loggerFactory == null)
{
_loggerFactory = new LoggerFactory();
}
foreach (var configureLogging in _configureLoggingDelegates)
{
configureLogging(_loggerFactory);
}
//The configured ILoggerFactory is added as a singleton here. AddLogging below will not add an additional one.
services.AddSingleton(_loggerFactory);
//This is required to add ILogger of T.
services.AddLogging();
services.AddTransient<IStartupLoader, StartupLoader>();
services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
services.AddTransient<IHttpContextFactory, HttpContextFactory>();
services.AddOptions();
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);
services.AddSingleton<DiagnosticListener>(diagnosticSource);
// Conjure up a RequestServices
services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();
// Ensure object pooling is available everywhere.
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
if (!string.IsNullOrEmpty(_options.ServerAssembly))
{
// Add the server
var serverType = ServerLoader.ResolveServerType(_options.ServerAssembly);
services.AddSingleton(typeof(IServer), serverType);
}
foreach (var configureServices in _configureServicesDelegates)
{
configureServices(services);
}
return services;
}
private string ResolveContentRootPath(string contentRootPath, string basePath)
{
if (string.IsNullOrEmpty(contentRootPath))
{
return basePath;
}
if (Path.IsPathRooted(contentRootPath))
{
return contentRootPath;
}
return Path.Combine(Path.GetFullPath(basePath), contentRootPath);
}
private string ResolveApplicationName()
{
if (_startup != null)
{
return _startup.ConfigureDelegate.GetMethodInfo().DeclaringType.GetTypeInfo().Assembly.GetName().Name;
}
if (_startupType != null)
{
return _startupType.GetTypeInfo().Assembly.GetName().Name;
}
if (!string.IsNullOrEmpty(_options.Application))
{
return _options.Application;
}
return null;
}
}
}