在WCF启动时运行功能 [英] Running a function on WCF start up

查看:138
本文介绍了在WCF启动时运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否可能,但是我想在启动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:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆