在 WCF 启动时运行函数

编程入门 行业动态 更新时间:2024-10-26 14:29:08
本文介绍了在 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:

  • 如果使用 .NET Framework 4.5,并且在 IIS 下:您可以使用服务运行时将调用的服务配置方法.更多信息请访问 msdn.microsoft/en-us/library/hh205277(v=vs.110).aspx.
  • 如果您是自托管服务,则您可以控制服务的启动时间(调用 ServiceHost.Open(),因此您可以在那里对其进行初始化
  • 如果您使用的是 IIS,而不是 4.5,则可以使用服务主机工厂和自定义服务主机,以便在打开服务主机时调用.那时您可以进行初始化.您可以在 中找到有关服务主机工厂的更多信息blogs.msdn/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 msdn.microsoft/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 blogs.msdn/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 启动时运行函数

本文发布于:2023-11-05 06:20:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:启动时   函数   WCF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!