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

查看:23
本文介绍了在 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天全站免登陆