4

I have a WCF/REST Web Service that I'm trying to add a global exception handler to. I'm looking for something similar to the Application_Error event in a standard .NET website.

I've found lots of info about using IErrorHandler and IServiceBehavior like what's detailed here: http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx#Y1479

That seems like what I need, but every example I've found assumes that the service is defined in the web.config. I'm not doing that - I'm using RouteTables, configured in the global.asax, like so:

 public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes();
    }

    private void RegisterRoutes()
    {
        // Edit the base address of Service1 by replacing the "Service1" string below

        RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHost2Factory(), typeof(myService)));


    }

So, given that, how do I configure my custom IErrorHandler and IServiceBehavior? Am I even on the right track, given that I'm using a RouteTable rather than configuring it via the web.config? I'm very new to WCF....

1 Answer 1

5

The wiring up of your IServiceBehaviour can be achieved by creating a custom WebServiceHostFactory that overrides CreateServiceHost.

For example if you have a class GlobalErrorHandlerBehaviour which implements IServiceBehavior, then you could wire it up as follows:

public class CustomWebServiceHostFactory : WebServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(System.Type serviceType, System.Uri[] baseAddresses)
    {
        return ApplyGlobalErrorHandler(base.CreateServiceHost(serviceType, baseAddresses));
    }

    private ServiceHost ApplyGlobalErrorHandler(ServiceHost serviceHost)
    {
        serviceHost.Description.Behaviors.Add(new GlobalErrorHandlerBehaviour());
        return serviceHost;
    }
}

You would then update your call to the ServiceRoute constructor to pass in this custom factory.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer. Please give this guy all the points! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.