Why are Static Methods not Usable as Web Service Operations in ASMX Web Services?
I just wanna learn why I can't static web methods in web services ? Why is it restricted ?
Can some body give me concise explanation of this.
Solution 1:
The answer is: because you can't.
It's not designed that way. The design is that an instance of the web service class will be created, and then an instance method will be called.
I can only guess why Microsoft designed it that way. To know for sure, you'd have to ask them. Consider:
- There's no particular benefit to permitting static methods. Anything you can do with a static method, you can also do with an instance method.
- A
[WebService]
class is not meant to be some arbitrary class that happens to be used as a web service. It's meant to be a class that you created for the purpose of exposing web service operations. As such, there is no need to support classes that already exist and already have static methods. - The SOAP Header implementation permits your class to contain an instance field of a type deriving from the
SoapHeader
class. This field will be filled with an incoming SOAP header and/or will contain the SOAP Header to be returned. You could not do this with a static field, as it would be overwritten with each request.
As I said, these are all guesses. The correct answer to the question is, "you can't because that's how Microsoft designed it. If you want to know why they designed it that way, you need to ask them".
FWIW, I just checked, and it does not appear that WCF permits static methods to be operations either.
Solution 2:
When a client creates an object for your web service, what they are really creating is a proxy object to that web service. This proxy object handles things like opening and closing your connections for you as well as all the overhead of actually working with the web service. A static method call would be difficult to manage. The "static proxy" for lack of a better word would have to do all of things that the instance of the proxy object is doing each and every time a client called one of the static methods, thus adding massive overhead.