在WCF启动时运行功能 [英] Running a function on WCF start up
问题描述
我不确定是否可能,但是我想在启动WCF服务以生成初始缓存数据后立即运行一个功能。我现在不担心如何实现缓存,我的问题严格是关于在服务启动时运行该功能。该服务将是RESTful。
I'm not sure if its possible, but I'd like to have a function run as soon as a WCF service is started to generate initial cache data. I'm not worried now about how to implement the cache, my question is strictly about having the function run when the service starts. The service will be RESTful.
该服务最终将托管在IIS中,并使用.Net Framework 4.5
The service will eventually be hosted in IIS and is using .Net Framework 4.5
推荐答案
@KirkWoll建议的方法有效,但前提是您在IIS中,这是App_Code下唯一的AppInitialize静态方法。如果要基于每个服务进行初始化,如果使用其他AppInitialize方法,或者如果您不在IIS下,则可以使用以下其他选项:
What @KirkWoll suggested works, but only if you're in IIS and that's the only AppInitialize static method under App_Code. If you want to do initialization on a per-service basis, if you have a different AppInitialize method or if you're not under IIS, you have these other options:
- 如果使用.NET Framework 4.5,并且在IIS下:您可以使用服务配置方法,该方法将在服务运行时调用。有关更多信息,请参见 http://msdn.microsoft.com /en-us/library/hh205277(v=vs.110).aspx 。
- 如果您是自托管服务,则可以控制服务的启动时间(调用
ServiceHost.Open()
,因此您可以在其中初始化 - 如果您使用的是IIS,而不是4.5 ,您可以在打开服务主机时使用服务主机工厂和自定义服务主机进行调用。这时,您可以进行初始化。有关服务主机工厂的更多信息,请访问 http://blogs.msdn.com/b/carlosfigueira/archive/2011 /06/14/wcf-extensibility-servicehostfactory.aspx 。
- If using .NET Framework 4.5, and under IIS: You can use the service configuration method which will be called when the service is running. More info at http://msdn.microsoft.com/en-us/library/hh205277(v=vs.110).aspx.
- If you're self-hosting your service, you control when the service starts (the call to
ServiceHost.Open()
, so you can initialize it there - If you're under IIS, and not on 4.5, you can use a service host factory and a custom service host to be called when the service host is being opened. At that point you can do your initialization. You can find more about service host factories at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx.
自定义工厂的示例如下所示:
An example of a custom factory is shown below:
public class MyFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
host.Opening += new EventHandler(host_Opening);
return host;
}
void host_Opening(object sender, EventArgs e)
{
// do initialization here
}
}
}
这篇关于在WCF启动时运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!