服务关闭之前执行操作

服务关闭之前执行操作

本文介绍了在 WCF 服务关闭之前执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 服务关闭之前执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:40