Recensie:
Begin met het koppelen van het ASP.NET Core GitHub open source adres
De hyperlink-login is zichtbaar.
De hyperlink-login is zichtbaar.
Na het aanmaken van een nieuw project ASP.NET Core 3.1 is de programmacode als volgt:
We hebben diep gedoken in de invoercode gecombineerd met de GitHub-broncode.
Hostcode:De hyperlink-login is zichtbaar.
CreateDefaultBuilder-methode
Hier instantieren we een HostBuilder-object, dat erft van IHostBuilder, en voegen we systeemgedefinieerde delegates toe, zoals :appsettings.json, appsettings. {env. EnvironmentName}.json configuratiebestand, dat uiteindelijk zal teruggeven: IHostBuilder-interface.
HostBuilder-code:De hyperlink-login is zichtbaar.
De Build-methode zal uiteindelijk worden aangeroepen.
publieke IHost Build()
{ als (_hostBuilt) { gooi nieuwe InvalidOperationException(SR. BuildCalled); } _hostBuilt = waar;
BuildHostConfiguration(); CreateHostingEnvironment(); CreateHostBuilderContext(); BuildAppConfiguration(); CreateServiceProvider();
retourneren _appServices.GetRequiredService<IHost>();
} BuildHostConfiguration-methode
privé IConfiguratie _hostConfiguration; IConfigurationBuilder configBuilder = nieuwe ConfigurationBuilder() Bel de delegate om op zijn beurt configuratie toe te voegen
CreateHostingEnvironment-methode
privé HostingEnvironment _hostingEnvironment; _hostingEnvironment = nieuwe HostingEnvironment()
{ ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey], EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? Omgevingen. Productie, ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory), }; CreateHostBuilderContext-methode
privé HostBuilderContext _hostBuilderContext; _hostBuilderContext = nieuwe HostBuilderContext(Properties)
{ HostingEnvironment = _hostingEnvironment, Configuratie = _hostConfiguration }; BuildAppConfiguration-methode
Integreer de configuratie-informatie opnieuw
IConfigurationBuilder configBuilder = nieuwe ConfigurationBuilder() . SetBasePath(_hostingEnvironment.ContentRootPath) . AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true); _appConfiguration = configBuilder.Build(); _hostBuilderContext.Configuration = _appConfiguration; CreateServiceProvider-methode
var services = nieuwe ServiceCollection(); Registreer een service, roep een delegate op en voeg een door de gebruiker gedefinieerde service toe.
GenericHostBuilderExtensions-extensiemethode
De hyperlink-login is zichtbaar.
ConfigureWebHost-extensiemethode
Om GenericWebHostService als backenddienst te registreren:
Bouwer. ConfigureServices((context, services) => services. AddHostedService<GenericWebHostService>()); GenericWebHostService-code:De hyperlink-login is zichtbaar.
publieke asynchrone TaakstartAsync(AnnuleringToken annuleringToken) { HostingEventSource.Log.HostStart();
var serverAddressesFeature = Server.Features.Get<IServerAddressesFeature>(); var addresses = serverAddressesFeature?. Adressen; als (adresseert!= null && !adressen. IsReadOnly && adressen. Aantal == 0) { var urls = Configuration[WebHostDefaults.ServerUrlsKey]; als (!string. IsNullOrEmpty(urls)) { serverAddressesFeature!. PreferHostingUrls = WebHostUtilities.ParseBool (Configuratie, WebHostDefaults.PreferHostingUrlsKey);
foreach (VAR-waarde in URL's. Split('; ', StringSplitOptions.RemoveEmptyEntries)) { adressen. Add(waarde); } } }
RequestDelegate? toepassing = nul;
Probeer het { var configure = Options.ConfigureApplication;
als (configureer == nul) { gooi nieuwe InvalidOperationException($"Geen applicatie geconfigureerd. Specificeer alstublieft een applicatie via IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, of specificeer de startup assembly via {nameof(WebHostDefaults.StartupAssemblyKey)} in de webhostconfiguratie."); }
var builder = ApplicationBuilderFactory.CreateBuilder(Server.Features);
foreach (var-filter in StartupFilters.Reverse()) { configureren = filteren. Configureer(configureer); }
configureer(bouwer);
Bouw de request pipeline Toepassing = bouwer. Build(); } vangen (Uitzondering bijv.) { Logger.ApplicationError(ex);
als (! Options.WebHostOptions.CaptureStartupErrors) { gooien; }
var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;
applicatie = ErrorPageBuilder.BuildErrorPageApplication(HostingEnvironment.ContentRootFileProvider, Logger, showDetailedErrors, bijv); }
var httpApplication = new HostingApplication(application, Logger, DiagnosticListener, HttpContextFactory);
await Server.StartAsync(httpApplication, cancellationToken);
als (adressen != nul) { foreach (var-adres in adressen) { LifetimeLogger.ListeningOnAddress(adres); } }
if (Logger.IsEnabled(LogLevel.Debug)) { foreach (var assembly in Options.WebHostOptions.GetFinalHostingStartupAssemblies()) { Logger.StartupAssemblyLoaded(assembly); } }
if (Options.HostingStartupExceptions != null) { foreach (var-uitzondering in Options.HostingStartupExceptions.InnerExceptions) { Logger.HostingStartupAssemblyError(uitzondering); } } }
var webhostBuilder = nieuwe GenericWebHostBuilder(builder, webHostBuilderOptions); De hyperlink-login is zichtbaar.
WebHostBuilderExtensions-extensiemethode
Biedt een startupType-object voor IWebHostBuilder-aanroepen.
deze IWebHostBuilder hostBuilder if (hostBuilder is ISupportsStartup supportsStartup)
{ return ondersteuntStartup.UseStartup(startupType);
} De hyperlink-login is zichtbaar.
GenericWebHostBuilder Privémethode GenericWebHostBuilder
Instantiateer ons Startup-object dynamisch:
Exemplaar ?? = ActivatorUtilities.CreateInstance (nieuwe HostServiceProvider(webHostBuilderContext), startupType); Context. Eigenschappen[_startupKey] = instantie; Zoek naar de ConfigureServices-methode
var configureServicesBuilder = StartupLoader.FindConfigureServicesDelegate(startupType, context. HostingEnvironment.EnvironmentName); var configureServices = configureServicesBuilder.Build(instance);
interne statische ConfigureServicesBuilder FindConfigureServicesDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string environmentName) { var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), vereist: false) ?? FindMethod(startupType, "Configure{0}Services", environmentName, typeof(void), vereist: false); geef nieuwe ConfigureServicesBuilder(servicesMethod) terug; Zoek naar de ConfigureContainer-methode
var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context. HostingEnvironment.EnvironmentName);
interne statische ConfigureContainerBuilder FindConfigureContainerDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string environmentName) { var configureMethod = FindMethod(startupType, "Configure{0}Container", environmentName, typeof(void), vereist: false); retourneren nieuwe ConfigureContainerBuilder(configureMethod); } Zoek naar de Configure-methode
configureBuilder = StartupLoader.FindConfigureDelegate(startupType, context. HostingEnvironment.EnvironmentName);
interne statische ConfigureBuilder ZoekConfigureDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Typ startupType, string environmentName)
{ var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), vereist: true)!; geef nieuwe ConfigureBuilder(configureMethod) terug;
} Aangeroepen door de Build-methode van ConfigureBuilder, is de broncode als volgt:
privéklasse ConfigureBuilder { publieke ConfigureBuilder(MethodInfo configure) { MethodInfo = configureren; }
public MethodInfo MethodInfo { get; }
publieke Action<IApplicationBuilder> Build (objectinstantie) { return (applicationBuilder) => Invoke (instance, applicationBuilder); }
private void Invoke (objectinstantie, IApplicationBuilder builder) { var serviceProvider = builder. ApplicationServices; var parameterInfos = MethodInfo.GetParameters(); var parameters = nieuw object[parameterInfos.Length]; voor (var-index = 0; index < parameterInfos.Lengte; index++) { var parameterInfo = parameterInfos[index]; als (parameterInfo.ParameterType == typeof(IApplicationBuilder)) { parameters[index] = bouwer; } anders { Probeer het { parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType); } vangen (Uitzondering bijv.) { gooi nieuwe InvalidOperationException( Resources.FormatMiddlewareFilter_ServiceResolutionFail( parameterInfo.ParameterType.FullName, parameterInfo.Name, MethodInfo.Name, MethodInfo.DeclaringType.FullName), bijv.); } } } MethodInfo.Invoke(instance, parameters); } } Run-methode
HostingAbstractionsHostExtensions extensie-uitbreidingsmethodeadres:
De hyperlink-login is zichtbaar.
Uiteindelijk belt:
/// <summary> Voert een applicatie uit en geeft een Taak terug die alleen wordt voltooid wanneer het token wordt geactiveerd of wanneer het afsluiten wordt geactiveerd. /// </summary> <param name="host">De <zie cref="IHost"/> om te runnen.</param> <param name="token">De token om de afsluiting te triggeren.</param> <returns>De <zie cref="Task"/> die de asynchrone bewerking vertegenwoordigt.</returns> publieke statische asynchrone Taak-RunAsync (deze IHost-host, AnnulatieToken = standaard) { Probeer het { Wacht op de gast. StartAsync (token). ConfigureAwait (vals);
Wacht op de gast. WachtOpSluitenAsync(token). ConfigureAwait (vals); } eindelijk { als (host is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync(). ConfigureAwait (vals); } anders { gastheer. Verwijderen(); }
} } Eerder, toen ik een dienst bouwde, registreerde ik me voor de IHost-dienst, en de code is als volgt:
diensten. AddSingleton<IHost>(_ => { Returneer nieuwe Interne.Host(_appServices, _appServices.GetRequiredService<IHostApplicationLifetime>(), _appServices.GetRequiredService<ILogger<Internal.Host>>(), _appServices.GetRequiredService<IHostLifetime>(), _appServices.GetRequiredService<IOptions<HostOptions>>()); }); StartAsync-methode
Adres:De hyperlink-login is zichtbaar.
publieke asynchrone TaakstartAsync(AnnuleringToken annuleringToken = standaard) { _logger. Start();
using var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping); AnnuleringToken gecombineerAnnuleringToken = gecombineerAnnuleringTokenBron.Token;
wacht op _hostLifetime.WachtOpStartAsync(gecombineerdeAnnuleringToken). ConfigureAwait (vals);
combinedCancellationToken.ThrowIfCancellationRequested(); _hostedServices = Services.GetService<IEnumerable<IHostedService>>();
foreach (IHostedService hostte Service in _hostedServices) { Branddienst Start await hostedService.StartAsync (combinedCancellationToken). ConfigureAwait (vals);
if (hostedService is BackgroundService backgroundService) { _ = HandleBackgroundException(backgroundService); } }
Vuur IHostApplicatieLifetime. Gestart _applicationLifetime. NotifyStarted();
_logger. Begonnen(); } (Einde)
|