How do I prevent a WCF service from enter a faulted state?

前端 未结 6 1612
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 08:23

I have a WCF Service that should not enter the faulted state. If there\'s an exception, it should be logged and the service should continue uninterrupted. The service has a

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 08:38

    Usually the WCF service is hosted in a ServiceHost, if the WCF-Service fails then the only option is to kill the WCF service and start a new one.

    The ServiceHost has an event trigger "Faulted" that is activated when the WCF Service fails:

    ServiceHost host = new ServiceHost(new Service.MyService());
    host.Faulted += new EventHandler(host_faulted);
    host.Open();
    

    It is possible to get the exception causing the fault, but it requires a bit more work:

    public class ErrorHandler : IErrorHandler
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
    
        }
    
        public bool HandleError(Exception error)
        {
            Console.WriteLine("exception");
            return false;
        }
    }
    
    public class ErrorServiceBehavior : IServiceBehavior
    {
        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
    
        }
    
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters)
        {
    
        }
    
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            ErrorHandler handler = new ErrorHandler();
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(handler);
            }
        }
    }
    
    ServiceHost host = new ServiceHost(new Service.MyService());
    host.Faulted += new EventHandler(host_faulted);
    host.Description.Behaviors.Add(new ErrorServiceBehavior());
    host.Open();
    

    Credits http://www.haveyougotwoods.ca/2009/06/24/creating-a-global-error-handler-in-wcf

提交回复
热议问题