.netwcfservicebehaviorendpointbehavior

Is there a .net equivalent of a Java initialization Servlet?


Is there a .net equivalent of a Java initialization Servlet?

While we're at it, the equivalent of a filter?

And finally if said thing exists (filters) can these run before/after a request is made to a WCF service?


Solution

  • While you can use the OnStart event of HttpApplication to intercept when the service starts as well as IHttpModule for intercepting requests, it is not the correct way to perform these interceptions in WCF.

    The only reason that recommendation works is because you are being hosted in IIS and using IIS-specific hooks. However, WCF services can be hosted anywhere, and you might find that you move your service to a service process, as well as change the bindings (you might use net-tcp instead of http, for example, in which case, how would you read the content coming in through an IHttpModule implementation? You couldn't) which would cause these hooks to break.

    That said, ideally you would perform any kind of initialization before you create your ServiceHost instance. However, since you don't have access to the ServiceHost instance in WCF in IIS, you will have to implement a custom ServiceHostFactory and specify that factory in your svc file (see the section titled Using a Custom ServiceHost in IIS or WAS). Taking this approach will make it portable.

    As for intercepting calls, you can do that on the client and on the service side. On the client side, you would implement IClientMessageInspector and on the server side you want IDispatchMessageInspector (I assume you want the latter).

    In order to "inject" this inspector on the service side, you would have to use an endpoint behavior (which would apply to a specific endpoint on the service, an implementation of IEndpointBehavior) or a service behavior (which applies to all endpoints on the service, through an implementation of the IServiceBehavior interface).

    It is through those implementations that you would look at the ServiceEndpoint (for endpoint behaviors) or ServiceDescription class to apply the implementation of your inspector, or any one of the other hooks available in WCF.

    You can read Paolo Pialorsi's "Writing a WCF Message Inspector" for a full walkthrough of how to pull this all together and give you insight into custom behaviors in WCF.