简体   繁体   中英

IIS module: Init() is called only once in a website?

I need to add an IIS module for some processing. Here is my module:

namespace MyNamespace
{
    public class MyModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            //I hope to do some work here ONLY once for all requests

            context.ReleaseRequestState += new EventHandler(myHandler);
        }

        #endregion

        public void myHandler(Object source, EventArgs e)
        {
            //do some work...
        }
    }
}

I need to do some resources-consuming work in the Init() method. I HOPE that Init is called ONLY once in a website and is called again only when the website is restarted in IIS Manager.

Can an expert in this tell me whether Init() works as I hope for?

Thanks!

For ANY requests being carried out, it will always call this method so no, it is not for the first time the app pool spins up. What you may wish to do is have a static variable in there to see if it truly is the first time its been hit and if not, carry on with what you need otherwise ignore it. ensure you lock around the portion of code when you are setting the variable to true.

Remember, IIS has application pools which websites use (generally speaking). There will be multiple concurrent requests coming into IIS to process and what happens? The app pool executes to serve the request to the website therefore multiple "hits" will be executed for the Init() for the HttpModule but once per application, if that makes sense.

Every one of them initializes their own list of modules.

you DO have the option of using the Application_Start event in the global asax which will only ever execute once per application (when the app pool spins up and the request is being submitted) - perhaps you can use this for your needs, which would be a better option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM