Windows Communication Foundation (WCF) Best Practices
1. 28 July, 2011 Windows Communication Foundation (WCF) Best Practices
2. Don't build a WCF service ! Unless you have a good reason for it: Security reasons (business Logic in perimeter network) Shared business logic (multiple apps or non .NET apps) Heavy resource consumption (long-running?) Separate maintainable Separate scalable 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 2
3. Know the tools! Svcutil.exe SvcConfigEditor.exe SvcTraceViewer.exe REST starter kit AppFabric Web Services Software Factory (WSSF) http://servicefactory.codeplex.com/ Enterprise Library (EntLib) Exception Handling Application Block Logging Application Block Validation Application Block 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 3
4. Additional tools on CodePlex http://wcfloadtest.codeplex.com takes a WCF trace file and a WCF client proxy, or a WCF interface contract, and generates a C# unit test that replays the same sequence of calls found in the trace file. The unit test can then be used to load-test the target http://wcfcontrib.codeplex.com/ library with infrastructure implementations for client and service communications http://wcfsecurity.codeplex.com/ http://wcfextensions.codeplex.com/ WCF Compression Channel 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 4
5. Service best practices Separate contract from implementation Contract (interface) first (http://wscfblue.codeplex.com/) Define services in a class library, not directly in a host project Layering Separate Service Layer Instance model Change to Per Call as default Session / Singleton – use only when needed 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 5
6. Exception Handling (I) For operation specific exceptions Try/catch, throw FaultException<T> Favor using FaultException<T> FaultException can be ambiguous to the client because unhandled exceptions arrive as a FaultException Include FaultContract in service contract definition 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 6
7. Exception Handling (II) If you throw FaultExceptions Part of the API you are exposing For global exception handling from services Use an error handler Include exception details in debug builds only !! 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 7
8. Hosting Favor WAS Hosting when on Windows Server 2008 Multiple protocol support IIS Hosting model and tools Use IIS hosting for external HTTP only Favor self-hosting for stateful services, callbacks, .NET Service Bus, debugging Have a console-based debug self-host for development time Can be a Windows Service project that is used for production self-hosting with a mode switch for debugging 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 8
9. When you self host … Do not put ServiceHost in a using statement in production code Dispose can throw an exception that masks the real exception thrown from Open call Explicitly call Close in try/catch and log/ deal with exception in catch 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 9
10. Client Proxy Classes (I) Use static proxy class when possible instead of ChannelFactory Connection caching in the base class in 3.5 Place for encapsulation of common patterns Hand-code or generate proxy classes for internal services Less bloated code Share service contract and data contracts through libraries Explicit control over config file 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 10
11. Client Proxy Classes (II) Add Service Reference for external services or when you want an async API on the client Clean up config after it messes it up Make sure to add references to data contract libraries before adding the service reference to avoid duplicate definitions Live with the duplicate service contract definition instead of needing to repeatedly clean up the proxy code 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 11
12. Client Proxy Management Cache client proxies if frequent calls to avoid session establishment cost If secure / reliable session enabled Have to deal more cautiously with faulted proxies Check proxy state before using Get rid of proxy after exception Don’t put proxies in a using statement Dispose call might throw exception and mask real exception Explicitly close in a try/catch block, and if Close throws an exception, Abort the proxy to ensure resource clean up 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 12
13. Client Exception Management All exceptions thrown from a service call derive from CommunicationException FaultException<T> always an explicit error returned from the service Simple approach: Any exception from a proxy call, safe close the proxy Advanced approach: FaultException<T> - proxy is reusable 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 13
14. Data Contracts Avoid XmlSerializer and MessageContracts except for interoperable scenarios and REST services Favor data contracts over serializable types More explicit model, better control over what the client sees Implement IExtensibleDataObject Avoids dropping data that the service / client does not understand Avoid passing complex .NET specific types for interoperable services DataSets and Exception types 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 14
15. SOAP vs REST Favor SOAP services when you are writing a service that only your code will consume Favor REST services for publicly exposed, data oriented services 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 15
16. Don't forget XmlNamespace settings By default WCF puts the “http://tempuri.org/” namespace in your wsdl and contracts. Normally you don’t want this. You can control this from three places: In your config file in the services/service/endpoint/bindingNamespaceattribute In your servicecontract: [ServiceContract(Namespace="http://myuri.net/")] In your servicebehavior: [ServiceBehavior(Namespace="http://myuri.net/")] 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 16
17. More subtle things with WCF One-way !? One-way is not always really one-way even when doing oneway, closing a client can block until the service side is done this is happening in quite some cases where bindings are configured to maintain sessions. it happens for example with Message security and or reliable session support (WS-ReliableMessaging). 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 17
18. The limits of reliable Messaging with WCF (I) Messages still can get lost with this mechanism if for example the service is shutdown IIS reset If you need end-to-end durable reliable messaging with full support for transactional I/O you need an infrastructure that's in control of both ends of the communication NetMsmqBinding. MSMQ messages are limited to 4 MB 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 18
19. The limits of reliable Messaging with WCF (II) If you are mostly worried about not losing messages under less-than-optimal networking conditions or require session support the reliable session support in WCF is the right choice isn’t very handy with load balancers Sticky session/session affinity 28 July, 2011 Windows Communication Foundation (WCF) Best Practices 19