Revízia:
Začnite pripojením open source adresy ASP.NET Core GitHub
Prihlásenie na hypertextový odkaz je viditeľné.
Prihlásenie na hypertextový odkaz je viditeľné.
Po vytvorení nového projektu ASP.NET Core 3.1 je kód programu nasledovný:
Dôkladne sme sa ponorili do vstupného kódu v kombinácii so zdrojovým kódom GitHubu.
Kód hostiteľa:Prihlásenie na hypertextový odkaz je viditeľné.
Metóda CreateDefaultBuilder
Tu inštancujeme objekt HostBuilder, ktorý dedí z IHostBuilder, a pridávame systémovo definovaných delegátov, ako sú :appsettings.json, appsettings. {env. EnvironmentName}.json konfiguračný súbor, ktorý nakoniec vráti: rozhranie IHostBuilder.
HostBuilder kód:Prihlásenie na hypertextový odkaz je viditeľné.
Metóda Build sa nakoniec bude volať.
public IHost Build()
{ ak (_hostBuilt) { throw new InvalidOperationException(SR. BuildCalled); } _hostBuilt = pravda;
BuildHostConfiguration(); CreateHostingEnvironment(); CreateHostBuilderContext(); BuildAppConfiguration(); CreateServiceProvider();
return _appServices.GetRequiredService<IHost>();
} Metóda BuildHostConfiguration
súkromné _hostConfiguration IConfigurácie; IConfigurationBuilder configBuilder = nový ConfigurationBuilder() Zavolajte delegáta, aby ste následne pridali konfiguráciu
Metóda CreateHostingEnvironment
súkromné HostingEnvironment _hostingEnvironment; _hostingEnvironment = nový HostingEnvironment()
{ ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey], EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production, ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory), }; Metóda CreateHostBuilderContext
súkromný HostBuilderContext _hostBuilderContext; _hostBuilderContext = nový HostBuilderContext(Vlastnosti)
{ HostEnvironment = _hostingEnvironment, Konfigurácia = _hostConfiguration }; Metóda BuildAppConfiguration
Znovu integrujte konfiguračné informácie
IConfigurationBuilder configBuilder = nový ConfigurationBuilder() . SetBasePath(_hostingEnvironment.ContentRootPath) . AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true); _appConfiguration = configBuilder.Build(); _hostBuilderContext.Konfigurácia = _appConfiguration; Metóda CreateServiceProvider
var services = new ServiceCollection(); Zaregistrujte službu, zavolajte delegáta a pridajte používateľsky definovanú službu.
Metóda rozšírenia GenericHostBuilderExtensions
Prihlásenie na hypertextový odkaz je viditeľné.
Metóda rozšírenia ConfigureWebHost
Na registráciu GenericWebHostService ako backend služby:
staviteľ. ConfigureServices((context, services) => services. AddHostedService<GenericWebHostService>()); GenericWebHostService kód:Prihlásenie na hypertextový odkaz je viditeľné.
public async Task StartAsync(CancellationToken cancellationToken) { HostingEventSource.Log.HostStart();
var serverAddressesFeature = Server.Features.Get<IServerAddressesFeature>(); var addresses = serverAddressesFeature?. Adresy; ak (adresy != null & !adresy. IsReadOnly & adresy. Count == 0) { var urls = Configuration[WebHostDefaults.ServerUrlsKey]; if (!string. IsNullOrEmpty(urls)) { serverAddressesFeature!. PreferHostingUrls = WebHostUtilities.ParseBool(Configuration, WebHostDefaults.PreferHostingUrlsKey);
Foreach (VAR hodnota v url. Split('; ', StringSplitOptions.RemoveEmptyEntries)) { adresy. Add(value); } } }
RequestDelege? aplikácia = null;
Skús { var configure = Options.ConfigureApplication;
ak (configure == null) { throw new InvalidOperationException($"Žiadna aplikácia nie je nakonfigurovaná. Prosím, zadajte aplikáciu cez IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, alebo zadajte štartovaciu zostavu pomocou {nameof(WebHostDefaults.StartupAssemblyKey)} v konfigurácia webhostingu."); }
var builder = ApplicationBuilderFactory.CreateBuilder(Server.Features);
foreach (var filter v StartupFilters.Reverse()) { configure = filter. Konfigurovať (konfigurovať); }
configure(builder);
Vybudujte pipeline požiadaviek aplikácia = staviteľ. build(); } chytiť (Výnimka ex) { Logger.ApplicationError(ex);
ak (! Options.WebHostOptions.CaptureStartupErrors) { hod; }
var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;
aplikácia = ErrorPageBuilder.BuildErrorPageApplication(HostingEnvironment.ContentRootFileProvider, Logger, showDetailedErrors, ex); }
var httpApplication = nová HostingApplication(application, Logger, DiagnosticListener, HttpContextFactory);
await Server.StartAsync(httpApplication, cancellationToken);
if (adresuje != null) { foreach (VAR adresa v adresách) { LifetimeLogger.ListeningOnAddress(adresa); } }
if (Logger.IsEnabled(LogLevel.Debug)) { foreach (var assembly in Options.WebHostOptions.GetFinalHostingStartupAssemblies()) { Logger.StartupAssemblyLoaded(assembly); } }
if (Options.HostingStartupExceptions != null) { foreach (var exception in Options.HostingStartupExceptions.InnerExceptions) { Logger.HostingStartupAssemblyError(exception); } } }
var webhostBuilder = nový GenericWebHostBuilder(builder, webHostBuilderOptions); Prihlásenie na hypertextový odkaz je viditeľné.
Metóda rozšírenia WebHostBuilderExtensions
Poskytuje objekt startupType pre volania IWebHostBuilder.
tento IWebHostBuilder hostBuilder ak (hostBuilder is ISupportsStartup supportsStartup)
{ return supportsStartup.UseStartup(startupType);
} Prihlásenie na hypertextový odkaz je viditeľné.
GenericWebHostBuilder Private Method GenericWebHostBuilder
Dynamicky inštancujte náš Startup objekt:
Inštancia ?? = ActivatorUtilities.CreateInstance(nový HostServiceProvider(webHostBuilderContext), startupType); Kontext. Vlastnosti[_startupKey] = inštancia; Hľadajte metódu ConfigureServices
var configureServicesBuilder = StartupLoader.FindConfigureServicesDelegate(startupType, context. HostingEnvironment.EnvironmentName); var configureServices = configureServicesBuilder.Build(instance);
internal static ConfigureServicesBuilder FindConfigureServicesDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Typ startupType, string environmentName) { var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false) ?? FindMethod(startupType, "Configure{0}Services", environmentName, typeof(void), required: false); return new ConfigureServicesBuilder(servicesMethod); Hľadajte metódu ConfigureContainer
var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context. HostingEnvironment.EnvironmentName);
internal static ConfigureContainerBuilder FindConfigureContainerDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Napíšte startupType, string environmentName) { var configureMethod = FindMethod(startupType, "Configure{0}Container", environmentName, typeof(void), required: false); vrátiť nový ConfigureContainerBuilder(configureMethod); } Hľadajte metódu Configure
configureBuilder = StartupLoader.FindConfigureDelegate(startupType, context. HostingEnvironment.EnvironmentName);
internal static ConfigureBuilder FindConfigureDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Typ startupu, string environmentName)
{ var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), required: true)!; return new ConfigureBuilder(configureMethod);
} Volaný metódou Build v ConfigureBuilder, zdrojový kód je nasledovný:
súkromná trieda ConfigureBuilder { public ConfigureBuilder(MethodInfo configure) { MethodInfo = konfigurovať; }
public MethodInfo MethodInfo { get; }
public<IApplicationBuilder> Action Build (inštancia objektu) { return (applicationBuilder) => Invoke(inštancia, applicationBuilder); }
private void Invoke(inštancia objektu, IApplicationBuilder builder) { var serviceProvider = builder. Aplikačné služby; var parameterInfos = MethodInfo.GetParameters(); parametre var = nový objekt[parameterInfos.Length]; pre (var index = 0; index < parameter Infos.Length; index++) { var parameterInfo = parameterInfos[index]; if (parameterInfo.ParameterType == typeof(IApplicationBuilder)) { parametre[index] = staviteľ; } else { Skús { parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType); } chytiť (Výnimka ex) { throw new InvalidOperationException( Resources.FormatMiddlewareFilter_ServiceResolutionFail( parameterInfo.ParameterType.FullName, parameterInfo.Name, MethodInfo.Name, MethodInfo.DeclaringType.FullName), ex); } } } MethodInfo.Invoke(inštancia, parametre); } } Metóda behu
Adresa metódy rozšírenia HostingAbstractionsHostExtensions:
Prihlásenie na hypertextový odkaz je viditeľné.
Nakoniec zavolá:
/// <summary> Spustí aplikáciu a vráti úlohu, ktorá sa dokončí len vtedy, keď sa spustí token alebo vypne. /// </summary> <param name="host"> <see cref="IHost"/> spustiť.</param> <názov parametra="token">Token na spustenie vypnutia.</param> <returns><pozri cref="Task"/> predstavuje asynchrónnu operáciu.</returns> public static async Task RunAsync (tento IHost hostiteľ, CancellationToken token = predvolený) { Skús { Čakajte na hostiteľa. StartAsync(token). ConfigureAwait(false);
Čakajte na hostiteľa. WaitForShutdownAsync(token). ConfigureAwait(false); } Nakoniec { ak (hostiteľ je IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync(). ConfigureAwait(false); } else { moderátor. Dispose(); }
} } Predtým, keď som budoval službu, registroval som sa do služby IHost a kód bol nasledovný:
služby. AddSingleton<IHost>(_ => { return new Internal.Host(_appServices, _appServices.GetRequiredService<IHostApplicationLifetime>(), _appServices.GetRequiredService<ILogger<Internal.Host>>(), _appServices.GetRequiredService<IHostLifetime>(), _appServices.GetRequiredService<IOptions<HostOptions>>()); }); Metóda StartAsync
Adresa:Prihlásenie na hypertextový odkaz je viditeľné.
public async Task StartAsync(CancellationToken cancellationToken = default) { _logger. Štarting();
použitím var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping); CancellationToken kombinovanýCancellationToken = kombinovanýCancellationTokenSource.Token;
await _hostLifetime.WaitForStartAsync(combinedCancellationToken). ConfigureAwait(false);
combinedCancellationToken.ThrowIfCancellationRequested(); _hostedServices = Services.GetService<IEnumerable<IHostedService>>();
foreach (IHostedService hostedService v _hostedServices) { // Fire IHostedService.Start await hostedService.StartAsync (combinedCancellationToken). ConfigureAwait(false);
ak (hostedService is BackgroundService backgroundServiceServices) { _ = HandleBackgroundException(backgroundService); } }
// Fire IHostApplicationLifetime.Started _applicationLifetime.NotifyStarted();
_logger. Started(); } (Koniec)
|