Performing action before WCF service is shutdown

本小妞迷上赌 提交于 2020-02-04 05:19:32

问题


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.

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?

Thanks

Shreedhar


回答1:


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).

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);
    }
}

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

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

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.



来源:https://stackoverflow.com/questions/11769673/performing-action-before-wcf-service-is-shutdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!