Веб-узел ASP.NET CoreASP.NET Core Web Host
Приложения ASP.NET Core настраивают и запускают узел.ASP.NET Core apps configure and launch a host. Узел отвечает за запуск приложения и управление временем существования.The host is responsible for app startup and lifetime management. Узел настраивает как минимум сервер и конвейер обработки запросов.At a minimum, the host configures a server and a request processing pipeline. Узел также может настроить ведение журнала, внедрение зависимостей и конфигурацию.The host can also set up logging, dependency injection, and configuration.
В этой статье описывается веб-узел, доступ к которому предоставляется только для обеспечения обратной совместимости.This article covers the Web Host, which remains available only for backward compatibility. Шаблоны ASP.NET Core создают универсальный узел .NET, который рекомендуется для всех типов приложений.The ASP.NET Core templates create a .NET Generic Host, which is recommended for all app types.
В этой статье описывается веб-узел, который предназначен для размещения веб-приложений.This article covers the Web Host, which is for hosting web apps. Для приложений других типов используйте универсальный узел.For other kinds of apps, use the Generic Host.
Создание узлаSet up a host
Создайте узел с помощью экземпляра IWebHostBuilder.Create a host using an instance of IWebHostBuilder. Обычно это делается в точке входа в приложение, то есть в методе Main
.This is typically performed in the app's entry point, the Main
method.
В шаблонах проектов метод Main
находится в файле Program.cs.In the project templates, Main
is located in Program.cs. Обычно приложение вызывает CreateDefaultBuilder, чтобы начать настройку узла:A typical app calls CreateDefaultBuilder to start setting up a host:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Код, который вызывает CreateDefaultBuilder
, находится в методе CreateWebHostBuilder
, что отделяет его от кода в методе Main
, который вызывает Run
для объекта построителя.The code that calls CreateDefaultBuilder
is in a method named CreateWebHostBuilder
, which separates it from the code in Main
that calls Run
on the builder object. Такое отделение требуется, если вы используете инструменты Entity Framework Core.This separation is required if you use Entity Framework Core tools. Эти инструменты используют метод CreateWebHostBuilder
, который они могут вызвать во время разработки для настройки узла без необходимости запускать приложение.The tools expect to find a CreateWebHostBuilder
method that they can call at design time to configure the host without running the app. В качестве альтернативного способа можно использовать реализацию IDesignTimeDbContextFactory
.An alternative is to implement IDesignTimeDbContextFactory
. Подробные сведения см. в статье Design-time DbContext Creation (Создание экземпляра DbContext во время разработки).For more information, see Design-time DbContext Creation.
Метод CreateDefaultBuilder
выполняет указанные ниже задачи.CreateDefaultBuilder
performs the following tasks:
- Настраивает сервер Kestrel в качестве веб-сервера с помощью поставщиков конфигурации размещения приложения.Configures Kestrel server as the web server using the app's hosting configuration providers. Параметры сервера Kestrel по умолчанию см. в разделе Настройка параметров для веб-сервера Kestrel для ASP.NET Core.For the Kestrel server's default options, see Настройка параметров для веб-сервера Kestrel для ASP.NET Core.
- Настраивает сервер Kestrel в качестве веб-сервера с помощью поставщиков конфигурации размещения приложения.Configures Kestrel server as the web server using the app's hosting configuration providers. Параметры сервера Kestrel по умолчанию см. в разделе Реализации веб-сервера Kestrel в ASP.NET Core.For the Kestrel server's default options, see Реализации веб-сервера Kestrel в ASP.NET Core.
- В качестве корневого каталога содержимого задает путь, возвращенный методом Directory.GetCurrentDirectory.Sets the content root to the path returned by Directory.GetCurrentDirectory.
- Загружает конфигурацию узла из:Loads host configuration from:
- Переменные среды с префиксом
ASPNETCORE_
(например,ASPNETCORE_ENVIRONMENT
).Environment variables prefixed withASPNETCORE_
(for example,ASPNETCORE_ENVIRONMENT
). - аргументы командной строки.Command-line arguments.
- Переменные среды с префиксом
- Загружает конфигурацию приложения в следующем порядке из:Loads app configuration in the following order from:
- appsettings.json.appsettings.json.
- appsettings.{Environment}.json;appsettings.{Environment}.json.
- секреты пользователя, когда приложение выполняется в среде
Development
с использованием начальных сборок;User secrets when the app runs in theDevelopment
environment using the entry assembly. - Переменные среды.Environment variables.
- аргументы командной строки.Command-line arguments.
- Настраивает ведение журнала для выходных данных консоли и отладки.Configures logging for console and debug output. Ведение журнала включает в себя правила фильтрации журналов, заданные в разделе конфигурации ведения журнала в файле appsettings.json или appsettings.{Environment}.json.Logging includes log filtering rules specified in a Logging configuration section of an appsettings.json or appsettings.{Environment}.json file.
- При работе за службами IIS с модулем ASP.NET Core
CreateDefaultBuilder
обеспечивает интеграцию со службами IIS для настройки базового адреса и порта приложения.When running behind IIS with the ASP.NET Core Module,CreateDefaultBuilder
enables IIS Integration, which configures the app's base address and port. Кроме того, интеграция со службами IIS также позволяет настраивать перехват приложением ошибок запуска.IIS Integration also configures the app to capture startup errors. Параметры IIS по умолчанию см. в разделе Размещение ASP.NET Core в Windows со службами IIS.For the IIS default options, see Размещение ASP.NET Core в Windows со службами IIS. - Устанавливает для ServiceProviderOptions.ValidateScopes значение
true
, если приложение находится в среде разработки.Sets ServiceProviderOptions.ValidateScopes totrue
if the app's environment is Development. Дополнительные сведения см. в разделе Проверка области.For more information, see Scope validation.
Настройки, определенные CreateDefaultBuilder
, можно переопределить и усилить с помощью ConfigureAppConfiguration, ConfigureLogging и других методов и методов расширения IWebHostBuilder.The configuration defined by CreateDefaultBuilder
can be overridden and augmented by ConfigureAppConfiguration, ConfigureLogging, and other methods and extension methods of IWebHostBuilder. Ниже приведены некоторые примеры:A few examples follow:
ConfigureAppConfiguration используется для указания дополнительного объекта
IConfiguration
для приложения.ConfigureAppConfiguration is used to specify additionalIConfiguration
for the app. Следующий вызовConfigureAppConfiguration
добавляет делегат, чтобы включить конфигурацию приложения в файл appsettings.xml.The followingConfigureAppConfiguration
call adds a delegate to include app configuration in the appsettings.xml file.ConfigureAppConfiguration
можно вызывать несколько раз.ConfigureAppConfiguration
may be called multiple times. Обратите внимание, что эта конфигурация не распространяется на узел (например, URL-адреса серверов или среду).Note that this configuration doesn't apply to the host (for example, server URLs or environment). См. раздел Значения конфигурации узла.See the Host configuration values section.WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true); }) ...
Следующий вызов
ConfigureLogging
добавляет делегата, чтобы настроить минимальный уровень ведения журнала (SetMinimumLevel) для LogLevel.Warning.The followingConfigureLogging
call adds a delegate to configure the minimum logging level (SetMinimumLevel) to LogLevel.Warning. Этот параметр переопределяет параметры в appsettings.Development.json (LogLevel.Debug
) и appsettings.Production.json (LogLevel.Error
), заданныеCreateDefaultBuilder
.This setting overrides the settings in appsettings.Development.json (LogLevel.Debug
) and appsettings.Production.json (LogLevel.Error
) configured byCreateDefaultBuilder
.ConfigureLogging
можно вызывать несколько раз.ConfigureLogging
may be called multiple times.WebHost.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Warning); }) ...
При следующем вызове к
ConfigureKestrel
переопределяется значение по умолчанию Limits.MaxRequestBodySize, равное 30 000 000 байтов, установленное при настройке Kestrel методомCreateDefaultBuilder
:The following call toConfigureKestrel
overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured byCreateDefaultBuilder
:WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = 20000000; });
Следующий вызов UseKestrel переопределяет значение по умолчанию Limits.MaxRequestBodySize, равное 30 000 000 байтов, установленное при настройке Kestrel методом
CreateDefaultBuilder
:The following call to UseKestrel overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured byCreateDefaultBuilder
:WebHost.CreateDefaultBuilder(args) .UseKestrel(options => { options.Limits.MaxRequestBodySize = 20000000; });
Корень содержимого определяет, где узел ищет файлы содержимого, например файлы представлений MVC.The content root determines where the host searches for content files, such as MVC view files. При запуске приложения из корневой папки проекта эта папка используется в качестве корня содержимого.When the app is started from the project's root folder, the project's root folder is used as the content root. Такое поведение по умолчанию принято в Visual Studio и шаблонах dotnet new.This is the default used in Visual Studio and the dotnet new templates.
Дополнительные сведения о конфигурации приложения см. в разделе Конфигурация в .NET Core.For more information on app configuration, see Конфигурация в .NET Core.
Примечание
Помимо использования статического метода CreateDefaultBuilder
, в ASP.NET Core 2.x поддерживается создание узла на основе WebHostBuilder.As an alternative to using the static CreateDefaultBuilder
method, creating a host from WebHostBuilder is a supported approach with ASP.NET Core 2.x.
При настройке узла можно предоставить методы Configure и ConfigureServices.When setting up a host, Configure and ConfigureServices methods can be provided. Если используется класс Startup
, в нем должен быть определен метод Configure
.If a Startup
class is specified, it must define a Configure
method. Для получения дополнительной информации см. Запуск приложения в ASP.NET Core.For more information, see Запуск приложения в ASP.NET Core. Несколько вызовов ConfigureServices
добавляются друг к другу.Multiple calls to ConfigureServices
append to one another. При нескольких вызовах Configure
или UseStartup
в WebHostBuilder
предыдущие параметры заменяются.Multiple calls to Configure
or UseStartup
on the WebHostBuilder
replace previous settings.
Значения конфигурации узлаHost configuration values
Для задания значений конфигурации узла класс WebHostBuilder поддерживает следующие подходы:WebHostBuilder relies on the following approaches to set the host configuration values:
- конфигурация построителя узла, которая включает в себя переменные среды в формате
ASPNETCORE_{configurationKey}
,Host builder configuration, which includes environment variables with the formatASPNETCORE_{configurationKey}
. Например,ASPNETCORE_ENVIRONMENT
.For example,ASPNETCORE_ENVIRONMENT
. - Расширения, такие как UseContentRoot и UseConfiguration (см. раздел Переопределение конфигурации).Extensions such as UseContentRoot and UseConfiguration (see the Override configuration section).
- метод UseSetting и связанный ключ.UseSetting and the associated key. Значение, задаваемое с помощью
UseSetting
, всегда является строкой независимо от типа.When setting a value withUseSetting
, the value is set as a string regardless of the type.
Хост использует значение, заданное последним.The host uses whichever option sets a value last. Дополнительные сведения см. в подразделе Переопределение конфигурации следующего раздела.For more information, see Override configuration in the next section.
Ключ приложения (имя)Application Key (Name)
Свойство IWebHostEnvironment.ApplicationName
задается автоматически при вызове UseStartup или Configure во время создания узла.The IWebHostEnvironment.ApplicationName
property is automatically set when UseStartup or Configure is called during host construction. Значение присваивается имени сборки, содержащей точку входа приложения.The value is set to the name of the assembly containing the app's entry point. Чтобы явно задать значение, используйте WebHostDefaults.ApplicationKey.To set the value explicitly, use the WebHostDefaults.ApplicationKey:
Свойство IHostingEnvironment.ApplicationName задается автоматически при вызове UseStartup или Configure во время создания узла.The IHostingEnvironment.ApplicationName property is automatically set when UseStartup or Configure is called during host construction. Значение присваивается имени сборки, содержащей точку входа приложения.The value is set to the name of the assembly containing the app's entry point. Чтобы явно задать значение, используйте WebHostDefaults.ApplicationKey.To set the value explicitly, use the WebHostDefaults.ApplicationKey:
Ключ: applicationNameKey: applicationName
Тип: stringType: string
По умолчанию: имя сборки, содержащей точку входа приложения.Default: The name of the assembly containing the app's entry point.
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_APPLICATIONNAME
Environment variable: ASPNETCORE_APPLICATIONNAME
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName")
Перехват ошибок при загрузкеCapture Startup Errors
Этот параметр управляет перехватом ошибок при загрузке.This setting controls the capture of startup errors.
Ключ: captureStartupErrorsKey: captureStartupErrors
Тип: bool (true
или 1
)Type: bool (true
or 1
)
По умолчанию: false
, если только приложение не работает с сервером Kestrel за службами IIS; в этом случае значение по умолчанию — true
.Default: Defaults to false
unless the app runs with Kestrel behind IIS, where the default is true
.
Задается с помощью: CaptureStartupErrors
Set using: CaptureStartupErrors
Переменная среды: ASPNETCORE_CAPTURESTARTUPERRORS
Environment variable: ASPNETCORE_CAPTURESTARTUPERRORS
Если задано значение false
, ошибки во время запуска приводят к завершению работы узла.When false
, errors during startup result in the host exiting. Если задано значение true
, узел перехватывает исключения во время запуска и пытается запустить сервер.When true
, the host captures exceptions during startup and attempts to start the server.
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
Корневой каталог содержимогоContent root
Этот параметр определяет то, где ASP.NET Core начинает искать файлы содержимого.This setting determines where ASP.NET Core begins searching for content files.
Ключ: contentRootKey: contentRoot
Тип: stringType: string
По умолчанию: папка, в которой находится сборка приложения.Default: Defaults to the folder where the app assembly resides.
Задается с помощью: UseContentRoot
Set using: UseContentRoot
Переменная среды: ASPNETCORE_CONTENTROOT
Environment variable: ASPNETCORE_CONTENTROOT
Корневой каталог содержимого также используется в качестве базового пути для корневого каталога документов.The content root is also used as the base path for the web root. Если путь к корневому каталогу содержимого не существует, узел не запускается.If the content root path doesn't exist, the host fails to start.
WebHost.CreateDefaultBuilder(args)
.UseContentRoot("c:\\<content-root>")
Дополнительные сведения можно найти в разделеFor more information, see:
Подробные сообщения об ошибкахDetailed Errors
Определяет, следует ли перехватывать подробные сообщения об ошибках.Determines if detailed errors should be captured.
Ключ: detailedErrorsKey: detailedErrors
Тип: bool (true
или 1
)Type: bool (true
or 1
)
Значение по умолчанию: falseDefault: false
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_DETAILEDERRORS
Environment variable: ASPNETCORE_DETAILEDERRORS
Если этот параметр включен (или если параметр Среда имеет значение Development
), приложение перехватывает подробные исключения.When enabled (or when the Environment is set to Development
), the app captures detailed exceptions.
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
СредаEnvironment
Задает среду приложения.Sets the app's environment.
Ключ: environmentKey: environment
Тип: stringType: string
По умолчанию: РабочиеDefault: Production
Задается с помощью: UseEnvironment
Set using: UseEnvironment
Переменная среды: ASPNETCORE_ENVIRONMENT
Environment variable: ASPNETCORE_ENVIRONMENT
В качестве среды можно указать любое значение.The environment can be set to any value. В платформе определены значения Development
, Staging
и Production
.Framework-defined values include Development
, Staging
, and Production
. Регистр символов в значениях не учитывается.Values aren't case sensitive. По умолчанию значение параметра Среда считывается из переменной среды ASPNETCORE_ENVIRONMENT
.By default, the Environment is read from the ASPNETCORE_ENVIRONMENT
environment variable. При использовании Visual Studio переменные среды можно задавать в файле launchSettings.json.When using Visual Studio, environment variables may be set in the launchSettings.json file. Для получения дополнительной информации см. Использование нескольких сред в ASP.NET Core.For more information, see Использование нескольких сред в ASP.NET Core.
WebHost.CreateDefaultBuilder(args)
.UseEnvironment(EnvironmentName.Development)
Начальные сборки размещенияHosting Startup Assemblies
Задает начальные сборки размещения для приложения.Sets the app's hosting startup assemblies.
Ключ: hostingStartupAssembliesKey: hostingStartupAssemblies
Тип: stringType: string
По умолчанию: Пустая строкаDefault: Empty string
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES
Environment variable: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES
Разделенная точками с запятой строка начальных сборок размещения, загружаемых при запуске.A semicolon-delimited string of hosting startup assemblies to load on startup.
Хотя значением по умолчанию этого параметра конфигурации является пустая строка, начальные сборки размещения всегда включают в себя сборку приложения.Although the configuration value defaults to an empty string, the hosting startup assemblies always include the app's assembly. Если начальные сборки размещения указаны, они добавляются к сборке приложения для загрузки во время построения приложением общих служб при запуске.When hosting startup assemblies are provided, they're added to the app's assembly for loading when the app builds its common services during startup.
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2")
HTTPS-портHTTPS Port
Задайте порт перенаправления HTTPS.Set the HTTPS redirect port. Используется при принудительном применении HTTPS.Used in enforcing HTTPS.
Ключ: https_portKey: https_port
Тип: stringType: string
По умолчанию: значение по умолчанию не задано.Default: A default value isn't set.
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_HTTPS_PORT
Environment variable: ASPNETCORE_HTTPS_PORT
WebHost.CreateDefaultBuilder(args)
.UseSetting("https_port", "8080")
Исключаемые начальные сборки размещенияHosting Startup Exclude Assemblies
Разделенная точками с запятой строка начальных сборок размещения, которые необходимо исключить при запуске.A semicolon-delimited string of hosting startup assemblies to exclude on startup.
Ключ: hostingStartupExcludeAssembliesKey: hostingStartupExcludeAssemblies
Тип: stringType: string
По умолчанию: Пустая строкаDefault: Empty string
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES
Environment variable: ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, "assembly1;assembly2")
Предпочитать URL-адреса размещенияPrefer Hosting URLs
Указывает, должен ли узел ожидать передачи данных по URL-адресам, настроенным с помощью WebHostBuilder
, вместо настроенных с помощью реализации IServer
.Indicates whether the host should listen on the URLs configured with the WebHostBuilder
instead of those configured with the IServer
implementation.
Ключ: preferHostingUrlsKey: preferHostingUrls
Тип: bool (true
или 1
)Type: bool (true
or 1
)
Значение по умолчанию: trueDefault: true
Задается с помощью: PreferHostingUrls
Set using: PreferHostingUrls
Переменная среды: ASPNETCORE_PREFERHOSTINGURLS
Environment variable: ASPNETCORE_PREFERHOSTINGURLS
WebHost.CreateDefaultBuilder(args)
.PreferHostingUrls(false)
Запретить запуск размещенияPrevent Hosting Startup
Запрещает автоматическую загрузку начальных сборок размещения, включая начальные сборки размещения, настроенные сборкой приложения.Prevents the automatic loading of hosting startup assemblies, including hosting startup assemblies configured by the app's assembly. Для получения дополнительной информации см. Использование начальных сборок размещения в ASP.NET Core.For more information, see Использование начальных сборок размещения в ASP.NET Core.
Ключ: preventHostingStartupKey: preventHostingStartup
Тип: bool (true
или 1
)Type: bool (true
or 1
)
Значение по умолчанию: falseDefault: false
Задается с помощью: UseSetting
Set using: UseSetting
Переменная среды: ASPNETCORE_PREVENTHOSTINGSTARTUP
Environment variable: ASPNETCORE_PREVENTHOSTINGSTARTUP
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true")
URL-адреса сервераServer URLs
Задает IP-адреса или адреса узлов с портами и протоколами, по которым сервер должен ожидать получения запросов.Indicates the IP addresses or host addresses with ports and protocols that the server should listen on for requests.
Ключ: urlsKey: urls
Тип: stringType: string
По умолчанию: http://localhost:5000Default: http://localhost:5000
Задается с помощью: UseUrls
Set using: UseUrls
Переменная среды: ASPNETCORE_URLS
Environment variable: ASPNETCORE_URLS
Укажите разделенный точками с запятой (;) список префиксов URL-адресов, на которые сервер должен отвечать.Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. Например, http://localhost:123
.For example, http://localhost:123
. Используйте символ "*", чтобы указать, что сервер должен ожидать получения запросов через определенный порт и по определенному протоколу по любому IP-адресу или имени узла (например, http://*:5000
).Use "*" to indicate that the server should listen for requests on any IP address or hostname using the specified port and protocol (for example, http://*:5000
). Протокол (http://
или https://
) должен указываться для каждого URL-адреса.The protocol (http://
or https://
) must be included with each URL. Поддерживаемые форматы зависят от сервера.Supported formats vary among servers.
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002")
Kestrel имеет собственный интерфейс API настройки конечных точек.Kestrel has its own endpoint configuration API. Для получения дополнительной информации см. Настройка конечных точек для веб-сервера Kestrel для ASP.NET Core.For more information, see Настройка конечных точек для веб-сервера Kestrel для ASP.NET Core.
Kestrel имеет собственный интерфейс API настройки конечных точек.Kestrel has its own endpoint configuration API. Для получения дополнительной информации см. Реализации веб-сервера Kestrel в ASP.NET Core.For more information, see Реализации веб-сервера Kestrel в ASP.NET Core.
Время ожидания завершения работыShutdown Timeout
Определяет, как долго необходимо ожидать завершения работы веб-узла.Specifies the amount of time to wait for Web Host to shut down.
Ключ: shutdownTimeoutSecondsKey: shutdownTimeoutSeconds
Тип: intType: int
По умолчанию: 5Default: 5
Задается с помощью: UseShutdownTimeout
Set using: UseShutdownTimeout
Переменная среды: ASPNETCORE_SHUTDOWNTIMEOUTSECONDS
Environment variable: ASPNETCORE_SHUTDOWNTIMEOUTSECONDS
Хотя ключ принимает значение int с UseSetting
(например, .UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")
), метод расширения UseShutdownTimeout принимает TimeSpan.Although the key accepts an int with UseSetting
(for example, .UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")
), the UseShutdownTimeout extension method takes a TimeSpan.
Во время ожидания размещение:During the timeout period, hosting:
- Активирует IApplicationLifetime.ApplicationStopping.Triggers IApplicationLifetime.ApplicationStopping.
- Пытается остановить размещенные службы, записывая в журнал все ошибки для служб, которые не удалось остановить.Attempts to stop hosted services, logging any errors for services that fail to stop.
Если время ожидания истекает до остановки всех размещенных служб, активные службы останавливаются при завершении работы приложения.If the timeout period expires before all of the hosted services stop, any remaining active services are stopped when the app shuts down. Службы останавливаются даже в том случае, если еще не завершили обработку.The services stop even if they haven't finished processing. Если службе требуется дополнительное время для остановки, увеличьте время ожидания.If services require additional time to stop, increase the timeout.
WebHost.CreateDefaultBuilder(args)
.UseShutdownTimeout(TimeSpan.FromSeconds(10))
Стартовая сборкаStartup Assembly
Определяет сборку, в которой необходимо искать класс Startup
.Determines the assembly to search for the Startup
class.
Ключ: startupAssemblyKey: startupAssembly
Тип: stringType: string
По умолчанию: сборка приложенияDefault: The app's assembly
Задается с помощью: UseStartup
Set using: UseStartup
Переменная среды: ASPNETCORE_STARTUPASSEMBLY
Environment variable: ASPNETCORE_STARTUPASSEMBLY
На сборку можно ссылаться по имени (string
) или типу (TStartup
).The assembly by name (string
) or type (TStartup
) can be referenced. При вызове нескольких методов UseStartup
приоритет имеет последний.If multiple UseStartup
methods are called, the last one takes precedence.
WebHost.CreateDefaultBuilder(args)
.UseStartup("StartupAssemblyName")
WebHost.CreateDefaultBuilder(args)
.UseStartup<TStartup>()
Корневой веб-узелWeb root
Задает относительный путь к статическим ресурсам приложения.Sets the relative path to the app's static assets.
Ключ: webrootKey: webroot
Тип: stringType: string
По умолчанию: Значение по умолчанию — wwwroot
.Default: The default is wwwroot
. Наличие пути {корневой_каталог_содержимого}/wwwroot обязательно.The path to {content root}/wwwroot must exist. Если этот путь не существует, используется фиктивный поставщик файлов.If the path doesn't exist, a no-op file provider is used.
Задается с помощью: UseWebRoot
Set using: UseWebRoot
Переменная среды: ASPNETCORE_WEBROOT
Environment variable: ASPNETCORE_WEBROOT
WebHost.CreateDefaultBuilder(args)
.UseWebRoot("public")
Дополнительные сведения можно найти в разделеFor more information, see:
Переопределение конфигурацииOverride configuration
Используйте конфигурацию для настройки веб-узла.Use Configuration to configure Web Host. В приведенном ниже примере необязательная конфигурация узла задается в файле hostsettings.json.In the following example, host configuration is optionally specified in a hostsettings.json file. Любую конфигурацию, загружаемую из файла hostsettings.json, можно переопределить с помощью аргументов командной строки.Any configuration loaded from the hostsettings.json file may be overridden by command-line arguments. Встроенная конфигурация (в config
) используется для настройки узла с помощью UseConfiguration.The built configuration (in config
) is used to configure the host with UseConfiguration. Конфигурация IWebHostBuilder
добавляется в конфигурацию приложения, но не наоборот —ConfigureAppConfiguration
не влияет на конфигурацию IWebHostBuilder
.IWebHostBuilder
configuration is added to the app's configuration, but the converse isn't true—ConfigureAppConfiguration
doesn't affect the IWebHostBuilder
configuration.
Конфигурация, предоставленная методом UseUrls
, сначала переопределяется конфигурацией из файла hostsettings.json, а затем с помощью аргументов командной строки:Overriding the configuration provided by UseUrls
with hostsettings.json config first, command-line argument config second:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hostsettings.json", optional: true)
.AddCommandLine(args)
.Build();
return WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:5000")
.UseConfiguration(config)
.Configure(app =>
{
app.Run(context =>
context.Response.WriteAsync("Hello, World!"));
});
}
}
hostsettings.json:hostsettings.json:
{
urls: "http://*:5005"
}
Примечание
UseConfiguration копирует ключи только из предоставленного объекта IConfiguration
в конфигурацию построителя узла.UseConfiguration only copies keys from the provided IConfiguration
to the host builder configuration. Поэтому указание reloadOnChange: true
для файлов JSON, XML и INI ни на что не влияет.Therefore, setting reloadOnChange: true
for JSON, INI, and XML settings files has no effect.
Чтобы указать узел, выполняющийся по определенному URL-адресу, можно передать нужное значение из командной строки при выполнении команды dotnet run.To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing dotnet run. Аргумент командной строки переопределяет значение urls
из файла hostsettings.json, и сервер будет ожидать передачи данных через порт 8080:The command-line argument overrides the urls
value from the hostsettings.json file, and the server listens on port 8080:
dotnet run --urls "http://*:8080"
Управление узломManage the host
ВыполнитьRun
Метод Run
запускает веб-приложение и блокирует вызывающий поток до тех пор, пока работа узла не будет завершена.The Run
method starts the web app and blocks the calling thread until the host is shut down:
host.Run();
ЗапускStart
Чтобы запустить узел без блокировки, вызовите метод Start
.Run the host in a non-blocking manner by calling its Start
method:
using (host)
{
host.Start();
Console.ReadLine();
}
Если в метод Start
передается список URL-адресов, он будет ожидать передачи данных по указанным URL-адресам.If a list of URLs is passed to the Start
method, it listens on the URLs specified:
var urls = new List<string>()
{
"http://*:5000",
"http://localhost:5001"
};
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
.Start(urls.ToArray());
using (host)
{
Console.ReadLine();
}
Приложение может инициализировать и запустить новый узел с использованием предварительно настроенных значений по умолчанию CreateDefaultBuilder
с помощью статического удобного метода.The app can initialize and start a new host using the pre-configured defaults of CreateDefaultBuilder
using a static convenience method. Эти методы запускают сервер без вывода данных в консоль и со временем ожидания прерывания, равным WaitForShutdown (Ctrl-C/SIGINT или SIGTERM):These methods start the server without console output and with WaitForShutdown wait for a break (Ctrl-C/SIGINT or SIGTERM):
Start(RequestDelegate app)Start(RequestDelegate app)
Выполните запуск с помощью RequestDelegate
:Start with a RequestDelegate
:
using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!")))
{
Console.WriteLine("Use Ctrl-C to shutdown the host...");
host.WaitForShutdown();
}
В браузере выполните запрос по адресу http://localhost:5000
, чтобы получить ответ "Hello World!"Make a request in the browser to http://localhost:5000
to receive the response "Hello World!" WaitForShutdown
блокируется, пока не будет создано прерывание (Ctrl-C/SIGINT или SIGTERM).WaitForShutdown
blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. Приложение выводит сообщение Console.WriteLine
и ожидает нажатия клавиши, после чего завершает работу.The app displays the Console.WriteLine
message and waits for a keypress to exit.
Start(string url, RequestDelegate app)Start(string url, RequestDelegate app)
Выполните запуск с помощью URL-адреса и RequestDelegate
:Start with a URL and RequestDelegate
:
using (var host = WebHost.Start("http://localhost:8080", app => app.Response.WriteAsync("Hello, World!")))
{
Console.WriteLine("Use Ctrl-C to shutdown the host...");
host.WaitForShutdown();
}
Результат будет тем же, что и при использовании Start(RequestDelegate app) , но приложение отвечает по адресу http://localhost:8080
.Produces the same result as Start(RequestDelegate app), except the app responds on http://localhost:8080
.
Start(Action<IRouteBuilder> routeBuilder)Start(Action<IRouteBuilder> routeBuilder)
Используйте экземпляр IRouteBuilder
(Microsoft.AspNetCore.Routing) для применения ПО промежуточного слоя маршрутизации:Use an instance of IRouteBuilder
(Microsoft.AspNetCore.Routing) to use routing middleware:
using (var host = WebHost.Start(router => router
.MapGet("hello/{name}", (req, res, data) =>
res.WriteAsync($"Hello, {data.Values["name"]}!"))
.MapGet("buenosdias/{name}", (req, res, data) =>
res.WriteAsync($"Buenos dias, {data.Values["name"]}!"))
.MapGet("throw/{message?}", (req, res, data) =>
throw new Exception((string)data.Values["message"] ?? "Uh oh!"))
.MapGet("{greeting}/{name}", (req, res, data) =>
res.WriteAsync($"{data.Values["greeting"]}, {data.Values["name"]}!"))
.MapGet("", (req, res, data) => res.WriteAsync("Hello, World!"))))
{
Console.WriteLine("Use Ctrl-C to shutdown the host...");
host.WaitForShutdown();
}
В этом примере используйте следующие запросы в браузере:Use the following browser requests with the example:
ЗапросRequest | ОтветResponse |
---|---|
http://localhost:5000/hello/Martin |
Hello, Martin!Hello, Martin! |
http://localhost:5000/buenosdias/Catrina |
Buenos dias, Catrina!Buenos dias, Catrina! |
http://localhost:5000/throw/ooops! |
Вызывает исключение со строкой "ooops!"Throws an exception with string "ooops!" |
http://localhost:5000/throw |
Вызывает исключение со строкой "Uh oh!"Throws an exception with string "Uh oh!" |
http://localhost:5000/Sante/Kevin |
Sante, Kevin!Sante, Kevin! |
http://localhost:5000 |
Пример "Здравствуй,Hello World! |
WaitForShutdown
блокируется, пока не будет создано прерывание (Ctrl-C/SIGINT или SIGTERM).WaitForShutdown
blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. Приложение выводит сообщение Console.WriteLine
и ожидает нажатия клавиши, после чего завершает работу.The app displays the Console.WriteLine
message and waits for a keypress to exit.
Start(string url, Action<IRouteBuilder> routeBuilder)Start(string url, Action<IRouteBuilder> routeBuilder)
Используйте URL-адрес и экземпляр IRouteBuilder
:Use a URL and an instance of IRouteBuilder
:
using (var host = WebHost.Start("http://localhost:8080", router => router
.MapGet("hello/{name}", (req, res, data) =>
res.WriteAsync($"Hello, {data.Values["name"]}!"))
.MapGet("buenosdias/{name}", (req, res, data) =>
res.WriteAsync($"Buenos dias, {data.Values["name"]}!"))
.MapGet("throw/{message?}", (req, res, data) =>
throw new Exception((string)data.Values["message"] ?? "Uh oh!"))
.MapGet("{greeting}/{name}", (req, res, data) =>
res.WriteAsync($"{data.Values["greeting"]}, {data.Values["name"]}!"))
.MapGet("", (req, res, data) => res.WriteAsync("Hello, World!"))))
{
Console.WriteLine("Use Ctrl-C to shut down the host...");
host.WaitForShutdown();
}
Результат будет тем же, что и при использовании Start(Action<IRouteBuilder> routeBuilder) , но приложение отвечает по адресу http://localhost:8080
.Produces the same result as Start(Action<IRouteBuilder> routeBuilder), except the app responds at http://localhost:8080
.
StartWith(Action<IApplicationBuilder> app)StartWith(Action<IApplicationBuilder> app)
Предоставьте делегат для настройки IApplicationBuilder
:Provide a delegate to configure an IApplicationBuilder
:
using (var host = WebHost.StartWith(app =>
app.Use(next =>
{
return async context =>
{
await context.Response.WriteAsync("Hello World!");
};
})))
{
Console.WriteLine("Use Ctrl-C to shut down the host...");
host.WaitForShutdown();
}
В браузере выполните запрос по адресу http://localhost:5000
, чтобы получить ответ "Hello World!"Make a request in the browser to http://localhost:5000
to receive the response "Hello World!" WaitForShutdown
блокируется, пока не будет создано прерывание (Ctrl-C/SIGINT или SIGTERM).WaitForShutdown
blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. Приложение выводит сообщение Console.WriteLine
и ожидает нажатия клавиши, после чего завершает работу.The app displays the Console.WriteLine
message and waits for a keypress to exit.
StartWith(string url, Action<IApplicationBuilder> app)StartWith(string url, Action<IApplicationBuilder> app)
Предоставьте URL-адрес и делегат для настройки IApplicationBuilder
:Provide a URL and a delegate to configure an IApplicationBuilder
:
using (var host = WebHost.StartWith("http://localhost:8080", app =>
app.Use(next =>
{
return async context =>
{
await context.Response.WriteAsync("Hello World!");
};
})))
{
Console.WriteLine("Use Ctrl-C to shut down the host...");
host.WaitForShutdown();
}
Результат будет тем же, что и при использовании StartWith(Action<IApplicationBuilder> app) , но приложение отвечает по адресу http://localhost:8080
.Produces the same result as StartWith(Action<IApplicationBuilder> app), except the app responds on http://localhost:8080
.
Интерфейс IWebHostEnvironmentIWebHostEnvironment interface
Интерфейс IWebHostEnvironment
предоставляет сведения о среде веб-размещения приложения.The IWebHostEnvironment
interface provides information about the app's web hosting environment. Чтобы получить интерфейс IWebHostEnvironment
для использования его свойств и методов расширения, воспользуйтесь внедрением конструктора:Use constructor injection to obtain the IWebHostEnvironment
in order to use its properties and extension methods:
public class CustomFileReader
{
private readonly IWebHostEnvironment _env;
public CustomFileReader(IWebHostEnvironment env)
{
_env = env;
}
public string ReadFile(string filePath)
{
var fileProvider = _env.WebRootFileProvider;
// Process the file here
}
}
Для настройки приложения при запуске в соответствии со средой можно применять подход на основе соглашения.A convention-based approach can be used to configure the app at startup based on the environment. Кроме того, можно внедрить интерфейс IWebHostEnvironment
в конструктор Startup
для использования в ConfigureServices
:Alternatively, inject the IWebHostEnvironment
into the Startup
constructor for use in ConfigureServices
:
public class Startup
{
public Startup(IWebHostEnvironment env)
{
HostingEnvironment = env;
}
public IWebHostEnvironment HostingEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
if (HostingEnvironment.IsDevelopment())
{
// Development configuration
}
else
{
// Staging/Production configuration
}
var contentRootPath = HostingEnvironment.ContentRootPath;
}
}
Примечание
Помимо метода расширения IsDevelopment
, интерфейс IWebHostEnvironment
предоставляет методы IsStaging
, IsProduction
и IsEnvironment(string environmentName)
.In addition to the IsDevelopment
extension method, IWebHostEnvironment
offers IsStaging
, IsProduction
, and IsEnvironment(string environmentName)
methods. Для получения дополнительной информации см. Использование нескольких сред в ASP.NET Core.For more information, see Использование нескольких сред в ASP.NET Core.
Службу IWebHostEnvironment
также можно внедрять непосредственно в метод Configure
для настройки конвейера обработки:The IWebHostEnvironment
service can also be injected directly into the Configure
method for setting up the processing pipeline:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
// In Development, use the Developer Exception Page
app.UseDeveloperExceptionPage();
}
else
{
// In Staging/Production, route exceptions to /error
app.UseExceptionHandler("/error");
}
var contentRootPath = env.ContentRootPath;
}
IWebHostEnvironment
можно внедрить в метод Invoke
при создании пользовательского ПО промежуточного слоя:IWebHostEnvironment
can be injected into the Invoke
method when creating custom middleware:
public async Task Invoke(HttpContext context, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
// Configure middleware for Development
}
else
{
// Configure middleware for Staging/Production
}
var contentRootPath = env.ContentRootPath;
}
Интерфейс IHostingEnvironmentIHostingEnvironment interface
Интерфейс IHostingEnvironment предоставляет сведения о среде веб-размещения приложения.The IHostingEnvironment interface provides information about the app's web hosting environment. Чтобы получить интерфейс IHostingEnvironment
для использования его свойств и методов расширения, воспользуйтесь внедрением конструктора:Use constructor injection to obtain the IHostingEnvironment
in order to use its properties and extension methods:
public class CustomFileReader
{
private readonly IHostingEnvironment _env;
public CustomFileReader(IHostingEnvironment env)
{
_env = env;
}
public string ReadFile(string filePath)
{
var fileProvider = _env.WebRootFileProvider;
// Process the file here
}
}
Для настройки приложения при запуске в соответствии со средой можно применять подход на основе соглашения.A convention-based approach can be used to configure the app at startup based on the environment. Кроме того, можно внедрить интерфейс IHostingEnvironment
в конструктор Startup
для использования в ConfigureServices
:Alternatively, inject the IHostingEnvironment
into the Startup
constructor for use in ConfigureServices
:
public class Startup
{
public Startup(IHostingEnvironment env)
{
HostingEnvironment = env;
}
public IHostingEnvironment HostingEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
if (HostingEnvironment.IsDevelopment())
{
// Development configuration
}
else
{
// Staging/Production configuration
}
var contentRootPath = HostingEnvironment.ContentRootPath;
}
}
Примечание
Помимо метода расширения IsDevelopment
, интерфейс IHostingEnvironment
предоставляет методы IsStaging
, IsProduction
и IsEnvironment(string environmentName)
.In addition to the IsDevelopment
extension method, IHostingEnvironment
offers IsStaging
, IsProduction
, and IsEnvironment(string environmentName)
methods. Для получения дополнительной информации см. Использование нескольких сред в ASP.NET Core.For more information, see Использование нескольких сред в ASP.NET Core.
Службу IHostingEnvironment
также можно внедрять непосредственно в метод Configure
для настройки конвейера обработки:The IHostingEnvironment
service can also be injected directly into the Configure
method for setting up the processing pipeline:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// In Development, use the Developer Exception Page
app.UseDeveloperExceptionPage();
}
else
{
// In Staging/Production, route exceptions to /error
app.UseExceptionHandler("/error");
}
var contentRootPath = env.ContentRootPath;
}
IHostingEnvironment
можно внедрить в метод Invoke
при создании пользовательского ПО промежуточного слоя:IHostingEnvironment
can be injected into the Invoke
method when creating custom middleware:
public async Task Invoke(HttpContext context, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
// Configure middleware for Development
}
else
{
// Configure middleware for Staging/Production
}
var contentRootPath = env.ContentRootPath;
}
Интерфейс IHostApplicationLifetimeIHostApplicationLifetime interface
Интерфейс IHostApplicationLifetime
позволяет выполнять действия после запуска и завершения работы.IHostApplicationLifetime
allows for post-startup and shutdown activities. Три свойства этого интерфейса представляют собой токены отмены, которые служат для регистрации методов Action
, определяющих события запуска и завершения работы.Three properties on the interface are cancellation tokens used to register Action
methods that define startup and shutdown events.
Токен отменыCancellation Token | Условие инициации…Triggered when… |
---|---|
ApplicationStarted |
Узел полностью запущен.The host has fully started. |
ApplicationStopped |
Заканчивается нормальное завершение работы узла.The host is completing a graceful shutdown. Все запросы должны быть обработаны.All requests should be processed. Завершение работы блокируется до тех пор, пока это событие не завершится.Shutdown blocks until this event completes. |
ApplicationStopping |
Происходит нормальное завершение работы узла.The host is performing a graceful shutdown. Запросы могут все еще обрабатываться.Requests may still be processing. Завершение работы блокируется до тех пор, пока это событие не завершится.Shutdown blocks until this event completes. |
public class Startup
{
public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime)
{
appLifetime.ApplicationStarted.Register(OnStarted);
appLifetime.ApplicationStopping.Register(OnStopping);
appLifetime.ApplicationStopped.Register(OnStopped);
Console.CancelKeyPress += (sender, eventArgs) =>
{
appLifetime.StopApplication();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
}
private void OnStarted()
{
// Perform post-startup activities here
}
private void OnStopping()
{
// Perform on-stopping activities here
}
private void OnStopped()
{
// Perform post-stopped activities here
}
}
Метод StopApplication
запрашивает остановку приложения.StopApplication
requests termination of the app. Следующий класс использует StopApplication
для корректного завершения работы приложения при вызове метода класса Shutdown
:The following class uses StopApplication
to gracefully shut down an app when the class's Shutdown
method is called:
public class MyClass
{
private readonly IHostApplicationLifetime _appLifetime;
public MyClass(IHostApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
public void Shutdown()
{
_appLifetime.StopApplication();
}
}
Интерфейс IApplicationLifetimeIApplicationLifetime interface
Интерфейс IApplicationLifetime позволяет выполнять действия после запуска и завершения работы.IApplicationLifetime allows for post-startup and shutdown activities. Три свойства этого интерфейса представляют собой токены отмены, которые служат для регистрации методов Action
, определяющих события запуска и завершения работы.Three properties on the interface are cancellation tokens used to register Action
methods that define startup and shutdown events.
Токен отменыCancellation Token | Условие инициации…Triggered when… |
---|---|
ApplicationStartedApplicationStarted | Узел полностью запущен.The host has fully started. |
ApplicationStoppedApplicationStopped | Заканчивается нормальное завершение работы узла.The host is completing a graceful shutdown. Все запросы должны быть обработаны.All requests should be processed. Завершение работы блокируется до тех пор, пока это событие не завершится.Shutdown blocks until this event completes. |
ApplicationStoppingApplicationStopping | Происходит нормальное завершение работы узла.The host is performing a graceful shutdown. Запросы могут все еще обрабатываться.Requests may still be processing. Завершение работы блокируется до тех пор, пока это событие не завершится.Shutdown blocks until this event completes. |
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
appLifetime.ApplicationStarted.Register(OnStarted);
appLifetime.ApplicationStopping.Register(OnStopping);
appLifetime.ApplicationStopped.Register(OnStopped);
Console.CancelKeyPress += (sender, eventArgs) =>
{
appLifetime.StopApplication();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
}
private void OnStarted()
{
// Perform post-startup activities here
}
private void OnStopping()
{
// Perform on-stopping activities here
}
private void OnStopped()
{
// Perform post-stopped activities here
}
}
StopApplication запрашивает остановку приложения.StopApplication requests termination of the app. Следующий класс использует StopApplication
для корректного завершения работы приложения при вызове метода класса Shutdown
:The following class uses StopApplication
to gracefully shut down an app when the class's Shutdown
method is called:
public class MyClass
{
private readonly IApplicationLifetime _appLifetime;
public MyClass(IApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
public void Shutdown()
{
_appLifetime.StopApplication();
}
}
Проверка областиScope validation
CreateDefaultBuilder устанавливает для ServiceProviderOptions.ValidateScopes значение true
, если приложение находится в среде разработки.CreateDefaultBuilder sets ServiceProviderOptions.ValidateScopes to true
if the app's environment is Development.
Если для ValidateScopes
установлено значение true
, поставщик службы по умолчанию проверяет, что:When ValidateScopes
is set to true
, the default service provider performs checks to verify that:
- Службы с заданной областью не разрешаются из корневого поставщика службы, прямо или косвенно.Scoped services aren't directly or indirectly resolved from the root service provider.
- Службы с заданной областью не вводятся в одноэлементные объекты, прямо или косвенно.Scoped services aren't directly or indirectly injected into singletons.
Корневой поставщик службы создается при вызове BuildServiceProvider.The root service provider is created when BuildServiceProvider is called. Время существования корневого поставщика службы соответствует времени существования приложения или сервера — поставщик запускается с приложением и удаляется, когда приложение завершает работу.The root service provider's lifetime corresponds to the app/server's lifetime when the provider starts with the app and is disposed when the app shuts down.
Службы с заданной областью удаляются создавшим их контейнером.Scoped services are disposed by the container that created them. Если служба с заданной областью создается в корневом контейнере, время существования службы повышается до уровня одноэлементного объекта, поскольку она удаляется только корневым контейнером при завершении работы приложения или сервера.If a scoped service is created in the root container, the service's lifetime is effectively promoted to singleton because it's only disposed by the root container when app/server is shut down. Проверка областей службы перехватывает эти ситуации при вызове BuildServiceProvider
.Validating service scopes catches these situations when BuildServiceProvider
is called.
Чтобы всегда проверять области, в том числе в рабочей среде, настройте ServiceProviderOptions с UseDefaultServiceProvider в конструкторе узлов:To always validate scopes, including in the Production environment, configure the ServiceProviderOptions with UseDefaultServiceProvider on the host builder:
WebHost.CreateDefaultBuilder(args)
.UseDefaultServiceProvider((context, options) => {
options.ValidateScopes = true;
})