In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to run the code before the ASP.NET Core program starts". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to run the code before the ASP.NET Core program starts.
Step by Step, let's start with the conclusion.
Because this article is more about my step-by-step thinking in solving this problem, it does not involve the writing of the code, so the following content may not be very helpful to you, so I will tell you the way to achieve it in advance. For this problem, we can implement our requirements simply by placing the code we want to execute in the location of the comments in the following code.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
Public class Program
{
Public static void Main (string [] args)
{
Var host = CreateHostBuilder (args). Build ()
/ / do what you want
Host.Run ()
}
Public static IHostBuilder CreateHostBuilder (string [] args) = >
Host.CreateDefaultBuilder (args)
.ConfigureWebHostDefaults (webBuilder = >
{
WebBuilder.UseStartup ()
});
}
One man's fault is other man's lesson
Before we try to implement this functional requirement in ASP.NET Core, we can see if it can provide some reference for our subsequent functional implementation by how it is implemented in .NET Framework.
For applications using .NET Framework, a Global.asax file is generated after the project is created, in which there is a method such as Application_Start, and the method Application_Start is actually triggered when the application receives the first HTTP request, that is, when the system receives the user's request for the first time after running, it will trigger the code logic in Application_Start. No matter how many requests are received later, the method will not be triggered again.
For example, in this MVC project template built on .NET Framework, you need to execute registration routing information, register filters, register js using bundle compression, css files, and so on before the program runs.
But there is no native way to do this in ASP.NET Core projects, so how can we implement similar functions ourselves in ASP.NET Core applications?
The teacher of the future
Now that we know how it was implemented in previous versions, let's take a closer look at the function of each line of code executed in the Application_Start method, isn't it particularly like the various middleware we used in the ASP.NET Core project?
However, if you have used ASP.NET Core, you will know that the middleware in ASP.NET Core will be triggered every time it is requested. Although we can set the code logic in our custom middleware to write if there is no data in the cache and skip it directly, since the function of the middleware is not really implemented until the first visit, it will not be used at all. For my slightly obsessive-compulsive children's shoes, this is really unbearable.
Since middleware doesn't work, and all we need is to run it only once, when it comes to .NET Core, I don't know what your first impression is. For me, ubiquitous dependency injection may be my first impression when I started learning .NET Core in 18 years. We know that there are three lifecycles of dependency injection components in .NET Core: Singleton, Scoped and Transient. The specific explanation of these three lifecycles is still recommended by Mr. Jiang Jinnan in the blog Park (elevator direct).
For the service injected in Singleton mode, because it is similar to a global singleton, no matter where it is accessed later, it will access the same instance, so can we implement our requirements on this basis?
Unfortunately, there is actually a serious logical problem here. The ultimate goal of dependency injection is to decouple the service contract we defined from the implementation. Consumers who implement services only need to tell the dependency injection container the type of service they need (service interface or abstract service class) to automatically get a matching service instance.
To put it simply, the consumer has to tell the service provider that you are going to start using a certain service before I can provide you with the corresponding service, just like when we go to a restaurant, after ordering, there is no need to care that the cook cooks the food for you with natural gas or gas, but the key to serving the food lies in whether we order or not. Therefore, the problem ultimately falls on where in the program we should call the method we have set.
After going around, it seems that our ideas are getting more and more biased and farther and farther away from what we want to achieve. Now that the road is off-road, let's go back to the starting point, abandon our experience in the .NET Framework project, and start again from the start-up process of the ASP.NET Core project.
There are two very important objects in the startup process of ASP.NET Core application, and the corresponding projects of ASP.NET Core 3.x are Host and HostBuilder. The Host here is the carrier that carries our Web applications to run, while HostBuilder is used to build Host objects.
PS: because ASP.NET Core 3.0 began to add support for the gRPC framework and Windows Service, and to integrate with other non-Web server solutions, the original WebHost and WebHostBuilder were replaced with the new generic host (generic-host) configuration mode. Of course, you can still use WebHost and WebHostBuilder in version 3.x, but of course it's not recommended.
Because for an ASP.NET Core application, it's essentially just a console application, so now let's look at the most important file in a console application: Program.cs, the code in the Program class is as follows.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
Public class Program
{
Public static void Main (string [] args)
{
CreateHostBuilder (args). Build (). Run ()
}
Public static IHostBuilder CreateHostBuilder (string [] args) = >
Host.CreateDefaultBuilder (args)
.ConfigureWebHostDefaults (webBuilder = >
{
WebBuilder.UseStartup ()
});
}
There is very little code and the function is very simple. To put it simply, build a HostBuilder object in the Main method, and then run it to achieve the purpose of starting our Web application host.
Of course, in the process of building HostBuilder objects, you will configure the Kestrel server, set up ContentRoot, load configuration files, and a series of actions, because you are too bad, try it, but it is still difficult to explain. If you want to know more, it is recommended to eat together with these two articles in the blog park (200 lines of code) 7 objects-allows you to understand the nature of the ASP.NET Core framework, ASP.NET Core 2.0: 7. A picture sees through the secret behind the startup. Although the reference articles are based on the ASP.NET Core 2.x version of the explanation, but the final difference is not very large.
I don't know if you have found the most important point in this class for us, in the Main method, we build first, and then run it, so can we wait after the build is complete, call the function we want to implement first, and then run our program? Well, let's modify the code in the Main method.
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
Public class Program
{
Public static void Main (string [] args)
{
Var host = CreateHostBuilder (args). Build ()
/ / Get logger
/ /
Var logger = host.Services.GetRequiredService ()
Logger.LogInformation (", I ran before web host starting")
Host.Run ()
}
Public static IHostBuilder CreateHostBuilder (string [] args) = >
Host.CreateDefaultBuilder (args)
.ConfigureWebHostDefaults (webBuilder = >
{
WebBuilder.UseStartup ()
});
}
Thank you for your reading, the above is the content of "how to run the code before the start of the ASP.NET Core program". After the study of this article, I believe you have a deeper understanding of how to run the code before the start of the ASP.NET Core program. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.