|
I found that many friends, like me, mistakenly used IHttpModule.Init as a Application_Start alternative to do some application initialization operations in it. However, the nature of Application_Start events in IHttpModule.Init and Global.asax is different, and IHttpModule.Init cannot be used directly to replace Application_Start ASP.NET the initialization process of the application. Nor can it be simply used to conclude that the Init method is repeatedly called to conclude that ASP.NET program has been restarted. The reason is that IHttpModule.Init may be called multiple times when responding to a request ASP.NET, and it is very likely to happen during the actual website operation. Why is IHttpModule.Init called multiple times because each HttpApplication instance can only handle one request at a time, and ASP.NET supports a certain number of concurrent requests, so the HttpApplication instance will be created multiple times to respond to different requests when it is not enough to respond to concurrent requests. Each HttpApplication instance creates a new set of HttpModules and calls the Init method after being created. Application_Start will only be called after the first HttpApplication object is created, and subsequent HttpApplication instances will not trigger this event. I think the reuse of HttpApplication instances is a major reason for the misunderstanding of the use of IHttpModule's Init method, because we usually only have one request when debugging a program, and it is basically impossible to repeatedly execute HttpModule's Init method. In the actual website running environment, concurrent requests are common, and if the Init method is misused, it may cause strange problems in the actual environment. For specific details, please refer to MSDN's "Overview of the ASP.NET Application Lifecycle for IIS 5.0 and 6.0", which provides images in the article: You can also use Refelector to decompile the System.Web assembly and analyze the call relationship of the IHttpModule.Init method. You'll end up with the System.Web.HttpApplicationFactory.GetNormalApplicationInstance method, which shows how instances of HttpApplication are reused and created. In summary, IHttpModule.Init cannot simply be used as a replacement for Application_Start. A relatively simple way is to use a static bool type field as the initialization tag, and set the mark to true after the initialization required by the program in HttpModule, and do not repeat the initialization next time. However, code like registering the BeginRequest event still needs to be executed every time Init is executed, because the HttpModule instance at this time is different, if you judge the static initialization markup field without repeating the registration event, it will lead to strange problems like URL rewriting sometimes executed and sometimes not executed.
[Myth] Will the HttpApplication object Init method be executed only once?
Answer: It will be executed multiple times!!!!!
|