Reputation: 3150
Is there a way to force a WCF Host to fault? (More specifically a REST based WCF Host.) Is there an Exception type that can be thrown that will cause the host to fault? If an exception can't get the host into a faulted state, what could?
In the "Api_Root" function below, I've thrown several different types of exceptions, and they either get caught by the exception handler, or cause the whole process to fail(OutOfMemoryException).
Some example code. Its in VB, but any C# help would also be greatly appreciated.
<ServiceContract(Name:="API", NameSpace:="urn:test")>
Public Interface IWebServiceApi
<OperationContract()>
<WebGet(UriTemplate:="GetObject")>
Function Api_Root() As Object
End Interface
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerCall, IncludeExceptionDetailInFaults:=True)>
Public Class WebServiceApi
Implements IWebServiceApi
Public Function Api_Root() As Object Implements IWebServiceApi.Api_Root
//Throw Exception type that causes the Host to Fail
Return New Object()
End Function
End Class
Function StartService()
_Service = New WebServiceHost(GetType(WebServiceApi), baseAddresses)
_Service.Open()
AddHandler _Service.Opened, AddressOf Me.Opened
AddHandler _Service.Closed, AddressOf Me.Closed
AddHandler _Service.Faulted, AddressOf Me.Faulted
End Function
Sub Faulted(sender As Object, e As EventArgs)
//Handle the falted service here
End Sub
Upvotes: 2
Views: 1712
Reputation: 3048
The Failed state does not exist. But, if you are talking about a generic way to close the host you can try:
System.ServiceModel.OperationContext.Current.Host.Close();
If a failure is mandatory for you, than the state you're looking for is Faulted. The Host object (whose type is System.ServiceModel.Channels.CommunicationObject) has a method named Fault(), which isn't public, but you'll probably be able to call it with a bit of reflection. That should make the Host transitioning into the Faulted state.
UPDATE. You can also use a host derived from WebServiceHost:
class MyWebServiceHost : System.ServiceModel.Web.WebServiceHost
{
public MyWebServiceHost(Type serviceType, params Uri[] baseAddresses)
: base (serviceType, baseAddresses)
{
}
public void Fail()
{
base.Fault();
}
}
Upvotes: 4
Reputation: 127603
The only way to get a host in to the faulted state is if a exception occurs during the Open()
call or the ChannelDispatcher that accepts the incoming connections throws an exception during the channel creation process as a user connects.
If you want to trigger it your self the easiest way I could find (After looking at the reference source a bit) is subscribe to the Opening
event and throw a exception inside it. This will cause Open()
to fail which will cause the connection to go into the faulted state.
Upvotes: 1