C# How to initialize WebService

If you require "initialisation" the first time a given client connects to the Web Service:

Have an Initialise method that returns a token, such a a GUID, that's then required on every call made to the actual "does the work" method of your web service. You can then ensure that for that client the service is always initialised.

If you require it the first time the web service is ever called:

Add some code to your service, as a private method, that is called at the top of each public method. Within it check for the existance of something, such as a registry entry, file, database record or other persistant value. If it doesn't exist, perform your initialisation and then create the "something".

If you require it on the first call since IIS last recycled/started the Application Pool:

Have a static constructor for the class so that when it's first instantiated the static constructor runs and performs your initialisation.


If you are trying to initialize a resource that is used by the web service and you only want to initialize it once per application, you can use the Application_Start event on the Global.asax. Be aware that IIS will recycle the application pool whenever the application pool is eating up too many resources.

If you need to initialize class level variable, you can do it in the constructor of the web service. I would recommend against that, because your web service should be stateless. If you need to initialize a static resource once in your web service, you can use a static constructor.

If you need a single resource that is available once throughout your application, I would recommend you look into the singleton pattern.


When you create a WebService application in Visual Studio, by default a class named "Service" will be added. When you look at the code for this class (Service.cs), you'll see a constructor ("public Service()") with two commented-out lines. You can either put your initialization code here, or call a private method that you've defined inside the Service class. This constructor will be called only when your client makes its first call to any WebMethod in the Service class.