À propos des classes Program et Startup - initialisation d'une application ASP.NET. Partie I: Programme et IHostBuilder

Introduction. De quoi parle l'article.

Il n'y a pas si longtemps sur Habré, j'ai vu un article avec un titre prometteur "Qu'est-ce que la classe Startup et Program.cs dans ASP.NET Core"... J'ai toujours été intéressé et intéressé par ce qui se passe exactement sous le capot d'une bibliothèque ou d'un cadre particulier avec lequel je travaille. Et cela s'applique pleinement aux applications Web sur ASP.NET Core. Et j'espérais obtenir de nouvelles informations dans cet article sur le fonctionnement des classes mentionnées lors du démarrage d'une telle application. Cet article, malheureusement, m'a déçu: il ne réitère qu'une partie du manuel une fois de plus, je n'ai pas reçu de nouvelles informations à partir de là. Et en le lisant, j'ai pensé qu'il y a probablement d'autres personnes qui, comme moi, sont intéressées non seulement par savoir comment utiliser tel ou tel framework (ASP.NET Core dans ce cas), mais aussi par son fonctionnement. Et comme j'ai, pour diverses raisons, récemment plongé assez profondément dans la structure interne d'ASP.NET Core, j'ai pensé:que maintenant j'ai beaucoup à dire sur lui au-delà de la portée des manuels. Et c'est pourquoi j'ai décidé de commencer par écrire un article sur ce que sont vraiment les classes Startup et Program - pour ne pas en dire autant sur la façon de les utiliser (c'est dans de nombreux manuels, qui, il me semble, il y a inutile de dupliquer), mais principalement sur le fonctionnement de ces classes, et - dans le contexte de l'ensemble de l'application Web sur ASP.NET Core. Cependant, comme l'immensité ne peut être appréhendée, le sujet de cet article est limité. Tout d'abord, il se limite à une histoire uniquement sur les applications Web créées à l'aide d'un nouveau type de modèle d'application - Generic Host. Deuxièmement, l'article sera uniquement consacré à la manière dont se déroule l'initialisation de l'application web,car le rôle principal des classes en question est exactement cela - l'initialisation et le lancement de l'application hébergée. Alors, pour qui le sujet à l'étude, même dans un volume aussi limité, est intéressant - bienvenue sous cat.





.

- , . , - ( ):





TL;DR

( : - ).





, Generic Host .





  1. (Host), IHostBuilder





  2. , - IHostBuilder , - , . , , IHostBuilder.





  3. IHostBuilder -. , ( IHostBuilder). Generic Host ( - , Host).





  4. (), IHost, Build IHostBuilder .





  5. . : , , , , (options). IHost Build.





  6. , . : ; ; ; - .





  7. , StartAsync IHost. - IHostedService - StartAsync. , .





.





, , , . , :





:

ASP.NET Core - - , . , , , - . , - , , , . , , " ", . , , : ASP.NET. : - , , , , ( , ). : , -, Generic Host, .. - - : , , , , .





:

, : , , - ... - - - : , .. " ". ( ) ( ) .





. ASP.NET Core . , . , Visual Studio , ASP.NET Core ", , " . ASP.NET Core .





:

, : , ASP.NET Core ( ) , , /, , , (" "), , ( - -) ( - , , - -), - , - , , var, ( - ) , / / - , C#. , , , - , ;-). (-) .





, ASP.NET, - ;-) , GOTO DO 5 . , -, , , , , , , ;-) (, , , - , ). .





ASP.NET Core, , Generic Host, - (, , - . ), , - .





:

, , - , - " ". D "SOLID". : " ", " ". - . , , , : , , , , , , - : . , , - , , . , . .





( ) . , , .

.





:

, , . : , , - // - - IMHO . IDE, , , : , , , , , . , , ( , - ).





, ASP.NET, .





, , ASP.NET - , , , , " ": , , , , . .





, ASP.NET, Generic Host , -: Web Host. (Microsoft) ASP.NET Core ( 3.1.8) , . , , , , . Generic Host. , -, (Middleware), , : .





, , (, IHost), .NET Core, ( - , DI Container), (Configuration), (Options).





, - . , , . , - , , " " ( ) . , , , ( ), , -, , ( ), , -, , , - , - , , - . , , Middleware, ( ASP.NET) , .





...

, - . , , , ASP.NET program.cs Program, Main. , Visual Studio, , . , CreateHostBuilder: CreateDefaultBuilder Microsoft.Extension.Hosting.Host , IHostBuilder ( ), IHostBuilder IHostBuilder ( ), , , . CreateHostBuilder , , ORM Entity Framework Core (DbContext), ( ). , Main, IHostBuilder.Build , IHost. , , IHost : Run, , , . - .





: ?

- . , , , ASP.NET Core "" (Builder pattern). , IMHO , , ( , ). - , Builder pattern Dependency Injection ( ), ASP.NET Core - . .





. , - (// ), , . , - , ( - -) - .





-: ConfigureWebHostDefaults -, Startup ( , -, , , , Startup-).





.. - Startup-, , , Startup- - : -, , Startup-. , Startup- - .





: -.

ConfigureWebHost, , -, . , IDE() ( ) : , ( ) IWebHostBuilder. - . , , , , - .





, - - , - , -.





. , - -





,

( - .NET Framework 3.5) (Expression Trees) - , . -, , , , . "" ;-) .





, , - . , ASP.NET Core " ", " ".





:

: , . , : , - ( Startup-, ). , , : ( StackOverflow ..), , , . . " ": , -, , , , . , , , - , , - ! (, , , ): , , , - (), . (, ) : " ( ) ". , , . : , , , , , . , , , , .





:

, , , , Generic Host, , .





:





Figure.  1. Schéma du processus d'initialisation de l'hôte générique
. 1. Generic Host

-c - , , - , . , . , , . - , . . - : , . . - , . - / ( , , ). - .





Host.CreateHostBuilder , IHostBuilder. () AddFeature1..AddFeatureN. IHostBuilder , Build. Build , . IHost ( - , Host) StartAsync .





IHostBuilder, CreateDefaultBuilder (, Microsoft.Extensions.Hosting.Host), Microsoft.Extensions.Hosting.HostBuilder( , - IHostBuilder). CreateDefaultBuilder , ( . ). - - , new, , , " ".





, ..

, , . , , , , . : ". ". - . , - , - , , .





Build. , , IHost ( "") .





-

Host, . Microsoft "" , - "node" "", . - Host "", " ". - - "" - , , -. .





, - "" - - ( ) , , . List<>, ,





:

( ) - , , (, , ).





, : , , , . .1 (""), : . , IHostBuilder . .1 , . - , .





: IHostBuilder

IHostBuilder, . IHostBuilder, UseServiceProviderFactory ( ) -, - , IServiceProvider. . , , IHostBuilder ( , , ) - Properties( IDictionary<object,object>), , ( - , ). , , IHostBuilder . (, ): HostBuilderContext, - ( ), (Singleton) .





- IHostBuilder. IHostBuilder . - , - .





Generic Host

, , , Generic Host





ASP.NET Core ( .NET Core ) - , IConfiguration .NET Core -, -, .





: ,

( , IConfigurationProvider) .NET Core : (environment), , ... , IConfigurationProvider. - : (, ) . , (, ), , . - .. : - , . , , , , , IConfiguration. ( - ) : , : (Bind) .





. : - IConfigurationBuilder - IConfigurationSource. - Build - IConfiguration. - , .





, , , ASP.NET Core .NET Core - : IServiceProvider. , , , . , - , , , . ( ) GetService -, - .





IServiceCollection, - . , ( ), . , .





:
  1. ServiceDescriptor. , .





  2. - , . - . - , , , . - IEnumerable -, , - IEnumerable IEnumerable, , . , IServiceCollection





  3. . , (Singleton) ( ), - , , (Transient), (Scoped), () , , ServiceProvider IServiceScope CreateScope IServiceProvider. , , , .





  4. :





    ) : , , ;





    ) -: , IServiceProvider; ( ); - ;





    ) ( ): .





ASP.NET Core .NET Core ( - ) - (Options). , , , , () , , . , -, , , .NET, : , , , , , . ( , - IOptions<>, IOptionsSnapshot<>, IOptionsMonitor<>, ). -, , , - (options). -, , . . , (options), , . IServiceCollection, . , , IConfiguration ( - ), , -, . , .





, - ( ), IHost , Build IHostBuilder. Generic Host Microsoft.Extensions.Hosting.HostBuilder ( HostBuilder) Build .





Build. Build .





: Build

HostBuilder.Build , . HostBuilder _hostBuilt, false. , true, - InvalidOperationException. _hostBuilt true.





, , . , - , - - , - , , , , . , (Host Configuration, - ). - , ( ), , , . - . . , , ConfigureHostConfiguration IHostBuilder _configureHostConfigActions. .1 "" 1.





:

ConfigureHostConfiguration -, - IConfigurationBuilder.





BuildHostConfiguration().





:

- ConfigurationBuider( IConfigurationBuilder) - configBuilder( .1 ) - , ( ) - ( IConfiguration) , . , IConfigurationBuilder ( , , ). , , ( IConfigurationBuilder.Build()) ( - ).





_hostConfiguration .





- , , . - (), IHostEnvironment. CreateHostingEnvironment(). HostingEnvironment, IHostEnvironment IHostingEnvironment ( IHostEnvironment). ( - . ). (ApplicationName), (Environment) (ContentRootPath).





- (-, . ). , , ContentRootFileProvider PhysicalFileProvider ContentRootPath - , ( ) . _hostingEnvironment .





, - ( HostBuilderContext) CreateHostBuilderContext. , : Properties - - ( . " : IHostBuilder"), Environment - (IHostEnvironment), Configuration - () ( ). _hostBuilderContext. , , .





BuildAppConfiguration. , , ConfigureAppConfiguration IHostBuilder _configureAppConfigActions. .1 "" 2.





:

ConfigureAppConfiguration -, - HostBuilderContext IHostBuilder. - ConfigurationBuider( IConfigurationBuilder) IHostEnvironment.ContentRootPath . IConfigurationBuilder SetBasePath. "FileProvider" PhysicalPathProvider . IFileProvider - (- FileConfigurationSource) , , - - , - .





IConfigurationBuilder . .





:

ChainedConfigurationSource, , ChainedConfigurationSource , ( Dispose) ChainedConfigurationProvider, .





.





:

IConfigurationBuilder _configureAppConfigActions, . - . . IConfigurationBuilder.Build.





( IConfiguration) _appConfiguration .





, IHostBuilder.Build - . CreateServiceProvider. , , .





- , . IServiceProviderFactory. , , , -, , , . - , , , .. , : ( . ) , IServiceCollection . - - ContainerBuilder( -, T), Container. "-". , - : .NET Core , , , , . ASP.NET Core .





, , IServiceProviderFactory. , CreateBuilder, IServiceCollection services) -, ( ) . CreateServiceProvider - - ( IServiceProvider).





(IHost) IHostBuilder UseServiceProviderFactory ( - -), : , - , HostBuilderContext , , . , , ( .1 ).





:

, , _serviceProviderFactory, - IConfigureContainerAdapter. - , HostBuilder, , -, - - . IConfigureContainerAdapter IServiceProviderFactory, . - , CreateBuilder - HostBuilderContext: , , UseServiceProviderFactory. - , IConfigureContainerAdapter - Object. , , ConfigureContainerAdapter, ( ) - - UseServiceProviderFactory, , , CreateServiceProvider . -, UseServiceProviderFactory , - (. ) (- ).





DefaultServiceProviderFactory. - IServiceCollection, .. IServiceProviderFactory. - - ( - , ).





:

ServiceProviderOptions - (options) . -: ValidateScopes - , (Scoped) ( ) ValidateOnBuild - , . ServiceProviderOptions.Default, . , , .





CreateBuilder DefaultServiceProviderFactory, , . CreateServiceProvider BuildServiceProvider IServiceCollection.





: CreateServiceProvider

, BuildServiceProvider, IServiceCollection, CreateServiceProvider - "-". ServiceProviderOptions - .





IServiceProvider. , , .





CreateServiceProvider , . IServiceCollection - services( .1 ). () , .





:

, - ServiceCollection. : List ( ), IServiceCollection . - ( (Singleton) ). - - , , Build: IHostEnvironment IHostingEnvironment ( - HostingEnvironment _hostingEnvironment) HostBuilderContext ( , ) ( - _hostBuilderContext. -, , , . - , , , ( ): IHostLifetime ( - ConsoleLifetime), IHostApplicationLifetime ( - ApplicationLifetime) IApplicationLifetime ( , IHostApplicationLifetime - ApplicationLifetime - , IApplicationLifetime) IConfiguration - -, - _appConfiguration ( -). - Dispose . - (. CreateServiceProvider ). , IServiceCollection , (options) - AddOptions, (logging) - AddLogging





( (Singleton) , Generic Host - IHost: Internal.Host, .





- - IServiceCollection _configureServicesActions. .1 "" 3. ConfigureServices. , : HostBuilderContext IServiceCollection.





- - containerBuilder ( .1 ).





: -

CreateBuilder IConfigureContainerAdapter, _serviceProviderFactory - containerBuilder





- - , , IServiceCollection.





- - - - - _configureContainerActions. .1 "" 4. ConfigureContainer. "" ( ) ASP.NET Core , , . , , , Startup- , , , ( UseStartup IWebHostBuilder).





( - )

ConfigureContainer - , -, -. - -, : - HostBuilderContext -, - -, - - ConfigureContainer. , - , ( List<>, ), IConfigureContainerAdapter, ConfigureContainerAdapter, -, ( - ). . ConfigureContainer , - Object. ConfigureContainerAdapter - . : : , - , - -. . , ConfigureContainer ConfigureContainerAdapter - , , , , Build . , , Object - - . IMHO - .





, - .





: -

- : (Scoped) , , Singleton - , , , , (Scoped). - , ( Development) - , InvalidOperationException. ValidateScopes ServiceProviderOptions, DefaultServiceProviderFactory, BuildServiceProvider IServiceCollection, . CreateBuilder IConfigureContainerAdapter, _serviceProviderFactory, - containerBuilder





CreateServiceProvider .





:

- : IConfiguration - , _appConfiguration ( Dispose()) ( - )





, Build HostBuilder - IHost ( Internal.Host), .





:

, IHost Build . Internal.Host, , -, , , , , , . , , , . - : - Build, . Internal.Host, HostBuilder.Build - , (option) HostOptions: , . , - - - Timespan. IHost HostBuilder.Build , .





, IHost - , . , IHost.StartAsync - , , StartAsync. StartAsync IHost - Internal.Host - ( ) IHostedService.StartAsync: IHostedService. . , - . , StartAsync IHost , .





Et c'est là que l'histoire de l'initialisation d'une application construite selon le modèle d'hôte générique peut être considérée comme terminée - maintenant l'application est lancée et en cours d'exécution. N'est-ce pas vraiment très simple? Prenez votre temps, dans la suite de cet article, il y aura une histoire sur les fonctionnalités d'initialisation d'une application Web - et le sentiment de simplicité, le cas échéant, disparaîtra sûrement.





Suite: sera publié prochainement. Il a déjà été écrit (et même posté sur mon blog, mais sous une forme incomplètement peignée).








All Articles