Auto run a method in a webservice on startup
I want to create a web-service that run a specific method on startup.
this is the serv开发者_如何学Goice's interface:namespace MyClass
{
[ServiceContract]
public interface IService
{
[OperationContract]
string getData();
}
}
and on the service itself i want a specific method (not one of those) to run when the service loads (or deployed to IIS). is there a way to do so?
You need to be clear what really happens when a WCF service is hosting in IIS.
- IIS provides a service host that loads on demand
- when a request comes in, IIS instantiates the service host, which in turns instantiates an instance of your service class, passes it the parameters from the request, and then executes the appropriate method on the service class
As such, there is no point in time when the "service loads" and then just lingers around in memory. The "service" isn't just loaded when IIS starts up and then would be "present and ready" at all times...
So where do you want to plug in??
when the service host loads in IIS? In that case, you'd have to create your own custom service host and register it with IIS so that IIS would use your custom host instead of the WCF default service host
when the actual service class is instantiated to handle the request? THen put your logic into the constructor of your service class - it will be executed each time a service class is instantiated to handle a request
Though this might not be exactly what you want, you could use the class's constructor, perhaps:
public class Service : IService
{
public Service()
{
//code here will execute when an instance
//of this service class is instantiated
}
string getData() { ... }
}
It would be more clear if you could inform us of the method you wish to call, and any surrounding information about it, so that you don't get ill-advice. Specifics are nice.
Here's where I put some code in order to get (and cache) data on the webservice start (in VB). You do need to trigger the service by navigating to any valid or invalid
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
'Run this method on startup to cache the addresses
Address.GetAll()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module
精彩评论