在 WCF 服务关闭之前执行操作

编程入门 行业动态 更新时间:2024-10-22 20:41:48
本文介绍了在 WCF 服务关闭之前执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个 WCF 服务托管在 IIS7 中.该服务有一个静态类,其中包含一个包含字符串(某种日志)的静态列表.它会定期将条目写入文件或数据库.

I have a WCF service hosted in IIS7. The service has a static class with a static list containing strings (sort of log). It periodically write the entries to a file or db.

然而,当 IIS 决定回收应用程序或因任何原因终止时,静态字段中的条目将丢失.

However when the IIS decides the recyle the app or terminate for whatever reason, the entries in the static field are lost.

有什么办法可以处理服务关闭类事件并从内存中保存数据吗?

Is there any way I can handle the service shuttingdown kind event and persist the data from memory?

谢谢

斯里德哈尔

推荐答案

我已经通过 IIS 使用自定义服务主机实现了多个服务(最初我这样做是为了我可以实现 IErrorHandler 以进行全局错误处理).

I've implemented several services via IIS with a custom service host (originally I did this so I could implement IErrorHandler for global error handling).

您需要两件事 - ServiceHost 的实现和 ServiceHostFactory 的实现,后者将调用您的自定义服务主机.例如(仅显示代码的相关部分):

You'll need two things - an implementation of ServiceHost and an implementation of ServiceHostFactory, which will call your custom service host. For example (just the relevant parts of code shown):

public class MyCustomServiceHost : ServiceHost
{

    protected override void OnClosing()
    {

        // logic to save off your static data
        base.OnClosing();
    }
}

public class MyCustomServiceHostFactory : ServiceHostFactory
{

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {

        return new MyCustomServiceHost(serviceType, baseAddresses);
    }
}

在您的 .svc 文件中,您将拥有如下内容:

In your .svc file, you'd have something like this:

<%@ ServiceHost Service="MyCompany.MyServiceName" Factory="MyCompany.MyCustomServiceHostFactory" %>
<%@ Assembly Name="MyCustomServiceHost" %>

这是实现此目的的一种方法(这可以追溯到 .NET 3.5 天);很可能还有其他方法可以做到这一点,但至少这应该给你一些指导.

This is one way to do this (and this dates back to .NET 3.5 days); there are quite likely other ways to accomplish this, but at least this should give you some direction.

这篇关于在 WCF 服务关闭之前执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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