Szemle:
Kezdjük azzal, hogy csatolod a ASP.NET Core GitHub nyílt forráskódú címet
A hiperlink bejelentkezés látható.
A hiperlink bejelentkezés látható.
Miután létrehoztak egy új projektet a Core 3.1 ASP.NET után a programkód a következő:
Mélyen belemerültünk a belépési kód és a GitHub forráskód kombinációjába.
Host kód:A hiperlink bejelentkezés látható.
CreateDefaultBuilder method
Itt egy HostBuilder objektumot indítunk, amely az IHostBuilder-től örököl, és rendszer-definiált delegáltákat, például :appsettings.json, appsettings-eket adunk hozzá. {env. EnvironmentName}.json konfigurációs fájl, amely végül visszaadja az IHostBuilder interfészt.
HostBuilder kód:A hiperlink bejelentkezés látható.
A Build módszert végül elnevezzük.
nyilvános IHost Build()
{ if (_hostBuilt) { dobd be az új InvalidOperationException(SR. BuildCalled); } _hostBuilt = igaz;
BuildHostConfiguration(); CreateHostingEnvironment(); CreateHostBuilderContext(); BuildAppConfiguration(); CreateServiceProvider();
return _appServices.GetRequiredService<IHost>();
} BuildHostConfiguration method
privát IConfiguration _hostConfiguration; IConfigurationBuilder configBuilder = new ConfigurationBuilder() Hívd fel a delegált, hogy addig adjon beállítást
CreateHostingEnvironment metódus
privát HostingEnvironment _hostingEnvironment; _hostingEnvironment = új HostingEnvironment()
{ ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey], EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? Környezetek. Gyártás, ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory), }; CreateHostBuilderContext method
privát HostBuilderContext _hostBuilderContext; _hostBuilderContext = új HostBuilderContext(Properties)
{ HostingEnvironment = _hostingEnvironment, Konfiguráció = _hostConfiguration }; BuildAppConfiguration módszer
Integráld újra a konfigurációs információkat
IConfigurationBuilder configBuilder = new ConfigurationBuilder() . SetBasePath(_hostingEnvironment.ContentRootPath) . AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true); _appConfiguration = configBuilder.Build(); _hostBuilderContext.Konfiguráció = _appConfiguration; CreateServiceProvider módszer
var services = új ServiceCollection(); Regisztráljon egy szolgáltatást, hívjon egy delegáltát, és adjon hozzá egy felhasználó által definiált szolgáltatást.
GenericHostBuilderExtensions extension method
A hiperlink bejelentkezés látható.
ConfigureWebHost kiterjesztési módszer
A GenericWebHostService backend szolgáltatásként való regisztrációjához:
Építő. ConfigureServices((context, services) => szolgáltatások. AddHostedService<GenericWebHostService>()); GenericWebHostService Code:A hiperlink bejelentkezés látható.
public async Feladat StartAsync(CancellationToken cancellationToken) { HostingEventSource.Log.HostStart();
var serverAddressesFeature = Server.Features.Get<IServerAddressesFeature>(); var addresses = serverAddressesFeature?. Címek; if (címek != null && !címek. IsReadOnly && címek. Szám == 0) { var urls = Configuration[WebHostDefaults.ServerUrlsKey]; if (!string. IsNullOrEmpty(urls)) { serverAddressesFeature!. PreferHostingUrls = WebHostUtilities.ParseBool(Configuration, WebHostDefaults.PreferHostingUrlsKey);
foreach (var érték URL-ekben. Split('; ', StringSplitOptions.RemoveEmptyEntries)) { címek. Add(value); } } }
RequestDelegate? alkalmazás = null;
próbáld ki { var configure = Options.ConfigureApplication;
if (configure == null) { throw new InvalidOperationException($"Nincs alkalmazás konfigurálva. Kérjük, jelölje meg az alkalmazást az IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, vagy a startup assembly {nameof(WebHostDefaults.StartupAssemblyKey)} segítségével a webes hóterház konfiguráció."); }
var builder = ApplicationBuilderFactory.CreateBuilder(Server.Features);
foreach (var filter in StartupFilters.Reverse()) { configure = szűrő. Konfigurálás (konfigurálás); }
configure(builder);
A kérés csővezeték építése alkalmazás = építő. Build(); } catch (kivétel ex) { Logger.ApplicationError(ex);
ha (! Options.WebHostOptions.CaptureStartupErrors) { dobás; }
var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;
application = ErrorPageBuilder.BuildErrorPageApplication(HostingEnvironment.ContentRootFileProvider, Logger, showDetailedErrors, stb.); }
var httpApplication = új HostingApplication(application, Logger, DiagnosticListener, HttpContextFactory);
await Server.StartAsync(httpApplication, cancellationToken);
if (cím != null) { foreach (var cím a címekben) { LifetimeLogger.ListeningOnAddress(address); } }
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 = new GenericWebHostBuilder(builder, webHostBuilderOptions); A hiperlink bejelentkezés látható.
WebHostBuilderExtensions kiterjesztési módszer
StartupType objektumot biztosít az IWebHostBuilder hívásokhoz.
ez az IWebHostBuilder hostBuilder if (hostBuilder is ISupportsStartup supportsStartup)
{ return supportsStartup.UseStartup(startupType);
} A hiperlink bejelentkezés látható.
GenericWebHostBuilder Private Method GenericWebHostBuilder
Dinamikusan instansáljuk a Startup objektumunkat:
Instance ?? = ActivatorUtilities.CreateInstance(new HostServiceProvider(webHostBuilderContext), startupType); A kontextus. Properties[_startupKey] = instance; Keresd a ConfigureServices metódust
var configureServicesBuilder = StartupLoader.FindConfigureServicesDelegate(startupType, context. HostingEnvironment.EnvironmentName); var configureServices = configureServicesBuilder.Build(instance);
belső statikus ConfigureServicesBuilder FindConfigureServicesDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type, string környezetNév) { 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); Keresd meg a ConfigureContainer metódust
var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context. HostingEnvironment.EnvironmentName);
internal static ConfigureContainerBuilder FindConfigureContainerDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string környezetNév) { var configureMethod = FindMethod(startupType, "Configure{0}Container", environmentName, typeof(void), required: false); return new ConfigureContainerBuilder(configureMethod); } Keresd a Configure módszert
configureBuilder = StartupLoader.FindConfigureDelegate(startupType, context. HostingEnvironment.EnvironmentName);
internal static ConfigureBuilder FindConfigureDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string environmentName)
{ var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), required: true)!; return new ConfigureBuilder(configureMethod);
} A ConfigureBuilder Build módszerével megnevezett forráskód a következő:
private osztály ConfigureBuilder { public ConfigureBuilder(MethodInfo configure) { MethodInfo = konfigurálás; }
public MethodInfo MethodInfo { get; }
public Action<IApplicationBuilder> Build (objektum példány) { return (applicationBuilder) => Invoke(instance, applicationBuilder); }
private void Invoke(object instance, IApplicationBuilder builder) { var serviceProvider = builder. ApplicationServices; var parameterInfos = MethodInfo.GetParameters(); var paraméterek = új objektum[parameterInfos.Length]; esetén (var index = 0; index < paraméterInfos.Length; index++) { var parameterInfo = parameterInfos[index]; if (parameterInfo.ParameterType == typeof(IApplicationBuilder)) { paraméterek[index] = builder; } más { próbáld ki { parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType); } catch (kivétel ex) { throw new InvalidOperationException( Resources.FormatMiddlewareFilter_ServiceResolutionFail( parameterInfo.ParameterType.FullName, parameterInfo.Name, MethodInfo.Name, MethodInfo.DeclaringType.FullName), ex); } } } MethodInfo.Invoke(instance, parameters); } } Futtatási módszer
HostingAbstractionsHostExtensions kiterjesztési módszer címe:
A hiperlink bejelentkezés látható.
Végül hívja:
/// <summary> Futtat egy alkalmazást, és egy olyan feladatot ad vissza, amely csak akkor fejeződik be, ha a token aktiválódik vagy leállítják. /// </summary> <param name="host"> a <lásd cref="IHost"/> futtatáshoz.</param> <param name="token"> A token, amely a leállítást indítja el.</param> <returns>A <lásd cref="Feladat"/>, amely az aszinkron műveletet képviseli.</returns> public static asinkron Feladat RunAsync (ez az IHost hoszt, CancellationToken token = default) { próbáld ki { Várjuk a házigazda. StartAsync(token). ConfigureAwait (hamis);
Várjuk a házigazda. WaitForShutdownAsync(token). ConfigureAwait (hamis); } végre { if (host IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync(). ConfigureAwait (hamis); } más { Házigazda. Dobás (elhelyezés); }
} } Korábban, amikor szolgáltatást építettem, regisztráltam az IHost szolgáltatásra, és a kód a következő:
Szolgáltatások. <IHost>AddSingleton(_ => { return new Internal.Host(_appServices, _appServices.GetRequiredService<IHostApplicationLifetime>(), _appServices.GetRequiredService<ILogger<Internal.Host>>(), _appServices.GetRequiredService<IHostLifetime>(), _appServices.GetRequiredService<IOptions<HostOptions>>()); }); StartAsync módszer
Cím:A hiperlink bejelentkezés látható.
public async Feladat StartAsync(CancellationToken cancellationToken = default) { _logger. Starting();
var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping) használatával; CancellationToken combinedCancellationToken = combinedCancellationTokenSource.Token;
await _hostLifetime.WaitForStartAsync(combinedCancellationToken). ConfigureAwait (hamis);
combinedCancellationToken.ThrowIfCancellationRequested(); _hostedServices = Services.GetService<<IHostedService>IEnumerable>();
foreach (IHostedService hostedService _hostedServices-ben) { Tűzoltó, IHostedService.Start await hostedService.StartAsync(combinedCancellationToken). ConfigureAwait (hamis);
if (hostedService is BackgroundService backgroundService backgroundService) { _ = HandleBackgroundException(backgroundService); } }
Tűz IHostApplicationLifetime.Indult _applicationLifetime.NotifyStarted();
_logger. Start(); } (Vége)
|