当前位置:网站首页>. 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 .
边栏推荐
- 合成大西瓜小游戏微信小程序源码/微信游戏小程序源码
- log Network Execution Time
- Classical Chinese can be programmed???
- How to take the PMP Exam agile on June 25? Share your troubles
- Unity Text组件空格换行问题
- Three types of transactions in EF core (saveChanges, dbcontexttransaction, transactionscope)
- 点乘和叉乘
- 生成所有可能的二叉搜索树
- 逆向工具IDA、GDB使用
- Generate all possible binary search trees
猜你喜欢

EasyCVR程序以服务启动异常,进程启动却正常,是什么原因?

合成大西瓜小游戏微信小程序源码/微信游戏小程序源码

Acrel-3000WEB电能管理系统在都巴高速的应用
![组合总数II[每个元素只能用一次 + 去重复解集]](/img/06/a40e28a1882a4278883202bc9c72d3.png)
组合总数II[每个元素只能用一次 + 去重复解集]

点乘和叉乘

Three types of transactions in EF core (saveChanges, dbcontexttransaction, transactionscope)

Classical Chinese can be programmed???

PMP Exam related calculation formula summary! Must see before examination

Test - use case - detail frenzy

量化投资模型——高频交易做市模型相关(Avellaneda & Stoikov’s)研究解读&代码资源
随机推荐
Design of message push platform
APP性能优化之启动流程分析
How to ensure reliable power supply of Expressway
Golang type assertion
EasyCVR程序以服务启动异常,进程启动却正常,是什么原因?
Batch renaming of images by MATLAB
log Network Execution Time
冶金行业数字化供应链管理系统:平台精益化企业管理,助力产业高质量发展
工作中一些常用的工具函數
What is medical treatment? AI medical concept analysis AI
extern、struct等关键字
Interpreting the "four thoughts" of Wal Mart China President on the transformation and upgrading of physical retail
[technical grass planting] Tencent Yunhao wool (consumption) record on the double 11
Six necessary open source projects for private activities
Innovative lampblack supervision in the management measures for the prevention and control of lampblack pollution in Deyang catering service industry (Draft for comments)
暑假第一周
不同物体使用同一材质,有不同的表现
云原生架构(05)-应用架构演进
三维向量场中的通量
AI技术在医学领域有什么用?