当前位置:网站首页>. Net
. Net
2022-06-24 00:01:00 【Phil Arist】
Translated from Steve Gordon 2020 year 3 month 30 Japanese articles 《WHAT ARE .NET WORKER SERVICES?》
With .NET Core 3.0 Release ,ASP.NET The team introduced a new Worker Service Project template , The template serves as .NET SDK Part of the release . In this paper , I'll introduce you to this new template , And some practical service examples developed with it .
Please complete the following preparatory work first , So that you can understand this article .
1、 Download and install the latest .NET SDK:https://dotnet.microsoft.com/download
2、 Command line run dotnet new Worker -n "MyService" command , Create a Worker Service project .What is? .NET Core Worker Service?
Worker Service It's built using templates .NET project , The template provides some useful functions , You can make regular console applications more powerful .Worker Service Run on the host (Host) On the concept of , The host maintains the life cycle of the application . The host also provides some common features , Such as dependency injection 、 Logging and configuration .
Worker Service Usually long-running Services , Perform some regular workload .
§Worker Service Some examples of
Processing from the queue 、 Messages for service bus or event flow 、 event
The response object 、 File changes in the file store
Aggregate data in a data store
Enrich the data, extract the data in the pipeline
AI/ML Formatting and cleaning of data sets
We can also develop such a Worker Service, The service performs a process from beginning to end , Then close it . Combined with scheduling program , You can support regular batch workloads . for example , The scheduler starts the service every hour , Complete some calculation of summary data , Then close it .
Worker Service No user interface , Nor does it support direct user interaction , They are particularly suitable for designing microservice architectures . In microservice Architecture , Responsibilities are usually divided into different 、 Separately deployable 、 Scalable services . With the growth and development of microservice Architecture , Have a lot of Worker Service It will become more and more common .
Worker Service What templates provide ?
It can be used without using Worker Service Develop long-running in the case of templates Worker Service. stay .NET Core I did this in earlier versions of , Use the dependency injection container to manually host , Then start my processing workload .
By default ,Worker Service Templates contain useful basic components , For example, dependency injection , So we can focus on building business logic on it . It contains a host that manages the application life cycle .
Worker Service The template itself is quite basic , It only contains three core files out of the box .
1. Program.cs
The first is Program class . This class contains .NET Required for console applications Main Method entry point ,.NET The operation period is expected to start up .NET In the application Program Class .
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
stay Program Class , As Worker Service Part of the template is CreateHostBuilder Method , This method creates one IHostBuilder.IHostBuilder Interface defines a type , This type uses the generator pattern to generate IHost Example . This template calls Host Class static CreateDefaultBuilder Method to create a new HostBuilder.
then , It uses generators to configure IHost, The IHost Is used to run Worker Service Applications . The host provides functions such as dependency injection container and logging , It's like we can be in ASP.NET Core As used in the application . in fact , from .NET Core 3.0 Start ,ASP.NET Core Web Applications and .NET Core Worker Service All run in the same IHost Upper .
By default , It contains a service registration , I'll talk about it later in this article , Don't worry for a while .
from Main Call in method CreateDefaultBuilder Method , The host will be built and run immediately . When .NET Run time call Main When the method is used , Application startup , The host will remain running , Monitor the standard off signal ( For example, press CTRL+C key ).
2. appsettings.json
If you have used ASP.NET Core, Will be very familiar with appsettings.json file , It's one of the common sources of application configuration . The host is designed to , When you start the application , Load application configuration from multiple sources using any registered configuration provider . One of the providers is from appsettings.json Load the configuration , The contents of this document are provided by JSON form , Its structure contains keys and values that represent the configuration of the application . These values can be arbitrarily defined in the logical fragments of the relevant configuration (Sections) Inside .
stay Worker Service in , The same configuration source is checked at startup ( Including this appsettings.json File and environment variables ), And build the final configuration from different sources . Multiple default providers are loaded by default , As a result, multiple sources will also be loaded . if necessary , You can also customize the provider that the host uses to load configuration data .
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Default in template appsettings The file contains the configuration settings of the logging library , Default pair Worker Service You can use . The configuration here is to set the logging level for some logging contexts .
3. Worker.cs
Worker It's the one you're in by default ASP.NET Core New classes not found in project templates . It's the magic of the combination of hosted services and hosts , Provides Worker Service The basis of .
Let's take a look at its code :
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
This kind of from BackgroundService Abstract base class derivation .BackgroundService Class implements a IHostedService The interface of .
BackgroundService Include a name ExecuteAsync Abstract method of , We have to override the method in the subclass , It's like Worker Service Provided in the template Worker Class .ExecuteAsync Method returns a Task, stay BackgroundService Inside , Expect this Task It's some long-running workload . The Task Will be started and run in the background .
In the internal , The host will start IHostedService All registered implementations of ( Ranging from BackgroundService Types derived from abstract classes ). please remember ,BackgroundService For us IHostedService.
4. How to register for hosting services (IHostedService)?
The next obvious problem is , How to sign up IHostedService ? If we go back to Program.cs Code for , We will find the answer :
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
stay ConfigureServices In the method , You can register types with the dependency injection container .AddHostedService Is for IServiceCollection An extension method defined , It allows us to register an implementation IHostedService Class .
In this template Worker Class is registered as a hosted service .
When it starts , The host will find the registered IHostedService All instances of , And start them in sequence , here , Their long-running workloads run as background tasks .
Why build .NET Core Worker Service?
The simple answer is —— When and if they are needed ! If you need to develop a microservice , It has no user interface , And perform long-running work , that Worker Service Probably a good choice .
please remember ,Worker Service The bottom layer of is just a console application . The console application uses the host to transform the application into a running service , Until you get a stop signal . The host brings some features that you may already be familiar with , Like dependency injection . Use and ASP.NET Core The same logging and configuration extensions available in , Make the development can log information and need some configuration Worker Service It's quite easy . When it comes to building Worker Service when , There's almost always a need for that . for example , You may need to work with your Worker Service Any external services that interact with each other provide configuration ( Like a queue URL).
Worker Service Can be used from existing ASP.NET Core Application extraction responsibilities , Design a new one based on .NET Core The micro service .
summary
In this paper , I introduced Worker Service Project template , And some of its potential use cases . We explored the use of Worker Service Three default files included in the new project created by the template .
1.Worker Service What files are included in the template ?
Program.cs: The entry point to the console application , Create and run hosts to manage the application lifecycle and generate a long-running service .
appsettings.json: A... That provides application configuration values JSON file .
Worker.cs: Derive from BackgroundService Base class , Used to define a long-running workload that is executed as a background task .
2.Worker Service What is it? ?
Applications that don't require user interaction .
Using hosts to maintain the lifecycle of console applications , Until the host receives a signal to shut down . Turning console applications into long-running Services .
Include and ASP.NET Core Same function , Such as dependency injection 、 Logging and configuration .
Perform regular and long-running workloads .
边栏推荐
- Recommend 4 flutter heavy open source projects
- Quelques fonctions d'outils couramment utilisées au travail
- List<? extends T>和List<?super T>区别
- 人工智能技术岗位面试要注意什么?
- 1.< tag-动态规划和路径组合问题>lt.62. 不同路径 + lt.63. 不同路径 II
- 微信小程序 图片验证码展示
- == 和 equals 的区别是什么?
- WPF效果之Expander+ListBox
- [interview experience package] summary of experience of being hanged during interview (I)
- Startup process analysis of APP performance optimization
猜你喜欢

为实现“双碳”目标,应如何实现节能、合理的照明管控

Synthetic big watermelon games wechat applet source code / wechat game applet source code

High imitation Betta app

云原生架构(05)-应用架构演进

数据库中索引原理及填充因子

逆向工具IDA、GDB使用

How to ensure reliable power supply of Expressway

Facebook open source shimmer effect

1.< tag-动态规划和路径组合问题>lt.62. 不同路径 + lt.63. 不同路径 II

Quantitative investment model -- research interpretation of high frequency trading market making model (Avellaneda & Stoikov's) & code resources
随机推荐
Detailed explanation of index invalidation caused by MySQL
Innovative lampblack supervision in the management measures for the prevention and control of lampblack pollution in Deyang catering service industry (Draft for comments)
String s = new String(“xyz“) 创建了几个字符串对象?
为实现“双碳”目标,应如何实现节能、合理的照明管控
B2B transaction management system of electronic components industry: improve the data-based driving ability and promote the growth of enterprise sales performance
Visual explanation of clockwise inner curve in Green's formula hole digging method
复原IP地址[标准回溯+标准剪枝]
Docker Deployment redis
PMP Exam related calculation formula summary! Must see before examination
Different objects use the same material and have different performances
.NET 中的 Worker Service 介绍
迷茫的测试/开发程序员,不同人有着不同的故事、有着不同的迷茫......
生成所有可能的二叉搜索树
数据库中索引原理及填充因子
Dot and cross product
三维向量场中的通量
解决项目依赖报红问题
Unity text component space newline problem
Idea automatically generates unit tests, doubling efficiency!
What is medical treatment? AI medical concept analysis AI