Sobre as classes Program e Startup - inicializando um aplicativo ASP.NET. Parte I: Programa e IHostBuilder

Introdução. Sobre o que é este artigo.

Não muito tempo atrás, em Habré, vi um artigo com um título promissor "O que é a classe de inicialização e Program.cs no ASP.NET Core"... Sempre estive interessado e interessado no que exatamente está acontecendo sob o capô de uma biblioteca ou estrutura específica com a qual eu trabalho. E isso se aplica totalmente a aplicativos da Web no ASP.NET Core. E eu esperava obter algumas informações novas neste artigo sobre como as classes mencionadas funcionam ao iniciar esse aplicativo. Esse artigo, infelizmente, me decepcionou: apenas reiterou um trecho do manual mais uma vez, não recebi nenhuma informação nova de lá. E enquanto o lia, pensei que provavelmente existem outras pessoas que, como eu, estão interessadas não apenas em saber como usar esta ou aquela estrutura (ASP.NET Core neste caso), mas também em como ela funciona. E como eu, por vários motivos, recentemente me aprofundei na estrutura interna do ASP.NET Core, pensei:que agora tenho muito a dizer sobre ele além do escopo dos manuais. E é por isso que decidi começar escrevendo um artigo sobre o que realmente são as classes Startup e Program - para não dizer muito sobre como usá-las (isso está em vários manuais, que, ao que parece, há não adianta duplicar), mas principalmente sobre como essas classes funcionam e - no contexto de todo o aplicativo da Web no ASP.NET Core. No entanto, como a imensidão não pode ser apreendida, o assunto deste artigo é limitado. Em primeiro lugar, ele se limita a uma história apenas sobre aplicativos da web criados usando um novo tipo de modelo de aplicativo - Host Genérico. Em segundo lugar, o artigo será dedicado apenas a como ocorre a inicialização do aplicativo da web,porque a principal função das classes em questão é exatamente essa - inicialização e lançamento do aplicativo hospedado. Portanto, para quem o tema em consideração, mesmo em um volume tão limitado, é interessante - bem-vindo em cat.





Introdução. Continuação

Para começar, vou expandir um pouco a parte introdutória do artigo - porque nem tudo que eu queria escrever poderia caber antes do kata. Mas, antes de mais nada - um resumo do artigo (sob o spoiler):





TL; DR

(Aviso: não tem tudo aqui).





A inicialização de um aplicativo feito de acordo com o modelo de host genérico tem esta aparência.





  1. Um objeto Host Builder é criado para implementar a interface IHostBuilder





  2. Em seguida, o estágio de configuração é executado, no qual os componentes do aplicativo são configurados - seja chamando métodos da interface IHostBuilder diretamente, seja chamando métodos de extensão para essa interface - métodos estáticos definidos em outras classes. Esses métodos de extensão, como regra, executam a configuração chamando todos os mesmos métodos da interface 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, , .





:





FIG.  1. Diagrama do processo de inicialização do Host Genérico
. 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 , .





E é aí que a história sobre como inicializar um aplicativo construído de acordo com o modelo de host genérico pode ser considerada completa - agora o aplicativo está iniciado e em execução. Não é realmente muito simples? Não tenha pressa, na continuação deste artigo haverá uma história sobre os recursos de inicialização de um aplicativo da web - e a sensação de simplicidade, se houver, certamente desaparecerá.





Continuação: será publicado em breve. Já foi escrito (e até postado no meu blog, mas de forma incompleta).








All Articles