/// <summary> /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application. /// </summary> public IWebHost Build() { if (_webHostBuilt) { throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance); } _webHostBuilt = true; var hostingServices = BuildCommonServices(out var hostingStartupErrors); var applicationServices = hostingServices.Clone(); var hostingServiceProvider = hostingServices.BuildServiceProvider(); if (!_options.SuppressStatusMessages) { // Warn about deprecated environment variables 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'"); } if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) { Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'"); } } var logger = hostingServiceProvider.GetRequiredService <ILogger <WebHost> >(); // Warn about duplicate HostingStartupAssemblies foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies().GroupBy(a => a, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) { logger.LogWarning($"The assembly {assemblyName} was specified multiple times. Hosting startup assemblies should only be specified once."); } AddApplicationServices(applicationServices, hostingServiceProvider); var host = new WebHost( applicationServices, hostingServiceProvider, _options, _config, hostingStartupErrors); host.Initialize(); return(host); }
public virtual async Task StartAsync(CancellationToken cancellationToken = default) { Debug.Assert(_applicationServices != null, "Initialize must be called first."); HostingEventSource.Log.HostStart(); _logger = _applicationServices.GetRequiredService <ILoggerFactory>().CreateLogger("Microsoft.AspNetCore.Hosting.Diagnostics"); _logger.Starting(); var application = BuildApplication(); _applicationLifetime = _applicationServices.GetRequiredService <ApplicationLifetime>(); _hostedServiceExecutor = _applicationServices.GetRequiredService <HostedServiceExecutor>(); // Fire IHostedService.Start await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false); var diagnosticSource = _applicationServices.GetRequiredService <DiagnosticListener>(); var activitySource = _applicationServices.GetRequiredService <ActivitySource>(); var httpContextFactory = _applicationServices.GetRequiredService <IHttpContextFactory>(); var hostingApp = new HostingApplication(application, _logger, diagnosticSource, activitySource, httpContextFactory); await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false); _startedServer = true; // Fire IApplicationLifetime.Started _applicationLifetime?.NotifyStarted(); _logger.Started(); // Log the fact that we did load hosting startup assemblies. if (_logger.IsEnabled(LogLevel.Debug)) { foreach (var assembly in _options.GetFinalHostingStartupAssemblies()) { _logger.StartupAssemblyLoaded(assembly); } } if (_hostingStartupErrors != null) { foreach (var exception in _hostingStartupErrors.InnerExceptions) { _logger.HostingStartupAssemblyError(exception); } } }
private void ExecuteHostingStartups() { var webHostOptions = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty); if (webHostOptions.PreventHostingStartup) { return; } var exceptions = new List <Exception>(); var processed = new HashSet <Assembly>(); _hostingStartupWebHostBuilder = new HostingStartupWebHostBuilder(this); // Execute the hosting startup assemblies foreach (var assemblyName in webHostOptions.GetFinalHostingStartupAssemblies()) { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); if (!processed.Add(assembly)) { // Already processed, skip it continue; } foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>()) { var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType) !; hostingStartup.Configure(_hostingStartupWebHostBuilder); } } catch (Exception ex) { // Capture any errors that happen during startup exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex)); } } if (exceptions.Count > 0) { _hostingStartupErrors = new AggregateException(exceptions); } }
private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors) { hostingStartupErrors = null; _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name); if (!_options.PreventHostingStartup) { var exceptions = new List <Exception>(); // Execute the hosting startup assemblies foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies().Distinct(StringComparer.OrdinalIgnoreCase)) { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); foreach (var attribute in assembly.GetCustomAttributes <HostingStartupAttribute>()) { var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType); hostingStartup.Configure(this); } } catch (Exception ex) { // Capture any errors that happen during startup exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex)); } } if (exceptions.Count > 0) { hostingStartupErrors = new AggregateException(exceptions); } } var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory); // Initialize the hosting environment _hostingEnvironment.Initialize(contentRootPath, _options); _context.HostingEnvironment = _hostingEnvironment; var services = new ServiceCollection(); services.AddSingleton(_options); services.AddSingleton <IHostingEnvironment>(_hostingEnvironment); services.AddSingleton <Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment); services.AddSingleton(_context); var builder = new ConfigurationBuilder() .SetBasePath(_hostingEnvironment.ContentRootPath) .AddConfiguration(_config); _configureAppConfigurationBuilder?.Invoke(_context, builder); var configuration = builder.Build(); services.AddSingleton <IConfiguration>(configuration); _context.Configuration = configuration; var listener = new DiagnosticListener("Microsoft.AspNetCore"); services.AddSingleton <DiagnosticListener>(listener); services.AddSingleton <DiagnosticSource>(listener); services.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>(); services.AddTransient <IHttpContextFactory, HttpContextFactory>(); services.AddScoped <IMiddlewareFactory, MiddlewareFactory>(); services.AddOptions(); services.AddLogging(); // Conjure up a RequestServices services.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>(); services.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>(); // Ensure object pooling is available everywhere. services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>(); if (!string.IsNullOrEmpty(_options.StartupAssembly)) { try { var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName); if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo())) { services.AddSingleton(typeof(IStartup), startupType); } else { services.AddSingleton(typeof(IStartup), sp => { var hostingEnvironment = sp.GetRequiredService <IHostingEnvironment>(); var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName); return(new ConventionBasedStartup(methods)); }); } } catch (Exception ex) { var capture = ExceptionDispatchInfo.Capture(ex); services.AddSingleton <IStartup>(_ => { capture.Throw(); return(null); }); } } _configureServices?.Invoke(_context, services); return(services); }
/// <summary> /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application. /// </summary> public IWebHost Build() { if (_webHostBuilt) { throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance); } _webHostBuilt = true; var hostingServices = BuildCommonServices(out var hostingStartupErrors); var applicationServices = hostingServices.Clone(); var hostingServiceProvider = GetProviderFromFactory(hostingServices); if (!_options.SuppressStatusMessages) { // Warn about deprecated environment variables 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'"); } if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) { Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'"); } } AddApplicationServices(applicationServices, hostingServiceProvider); var host = new WebHost( applicationServices, hostingServiceProvider, _options, _config, hostingStartupErrors); try { host.Initialize(); var logger = host.Services.GetRequiredService <ILogger <WebHost> >(); // Warn about duplicate HostingStartupAssemblies foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies().GroupBy(a => a, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1)) { logger.LogWarning($"The assembly {assemblyName} was specified multiple times. Hosting startup assemblies should only be specified once."); } return(host); } catch { // Dispose the host if there's a failure to initialize, this should clean up // will dispose services that were constructed until the exception was thrown host.Dispose(); throw; } IServiceProvider GetProviderFromFactory(IServiceCollection collection) { var provider = collection.BuildServiceProvider(); var factory = provider.GetService <IServiceProviderFactory <IServiceCollection> >(); if (factory != null && !(factory is DefaultServiceProviderFactory)) { using (provider) { return(factory.CreateServiceProvider(factory.CreateBuilder(collection))); } } return(provider); } }