SlideShare a Scribd company logo
1 of 14
WCF BEST PRACTICE
Yu Guan | Microsoft MVP
Meet Yu Guan | @askguanyu
twitter.com/askguanyu
linkedin.com/in/yuguan
askguanyu.wordpress.com
devlib.codeplex.com
Microsoft MVP
Speaker, Blogger, Hacker, Coder, Maker, Gamer
Azure, IoT, Cross-platform Apps, GIS, Services
WCF ARCHITECTURE GUIDELINE
 Contract Segmentation
 Parameters and Return Values
 Data Mapping
 Service Invocation
 Service Granularity
 Transferring Large Data Sets
 Load Balancing
Contract Segmentation
  You should separate logically related interfaces, contracts, entities, messages,
and enumerations into individual projects.
  You should implement WCF Services as DLLs.
Parameters and Return Values
  You should mark your types with the DataContractAttribute and
DataMemberAttribute attributes to create a data contract, which is the portion of
the service contract that describes the data that your service operations
exchange.
  You should not use Out and Ref Parameters.
  You should not use System.IO.Stream and derived types as parameter or
return value.
  You should not use System.IO.Stream and derived types inside of data
contracts.
Data Mapping
  You should centralize your types into a common project in order to share the
same data elements.
  You should check Reuse types in referenced assemblies check box.
Service Invocation
  You should centralize your contracts into a separate project. The calling
service can then reference these contract projects, which allows you to invoke
the services without a proxy.
Service Granularity
  You should weigh the tradeoffs and benefits of many chatty calls versus a few
chunky calls.
Client Service 1
chatty calls
Service 2
chunky
calls
Transferring Large Data Sets
  You should consider using compressing when sending or receiving large data.
  You can consider using streaming mode, but keep in mind that streaming
mode has lots of restrictions
Load Balancing
No Security Transport Security
Message Security
DevLib.ServiceModel
 NuGet: https://www.nuget.org/packages/DevLib.ServiceModel/
 Source code:
https://devlib.codeplex.com/SourceControl/latest#Main/Source/DevLib.ServiceM
odel/
Address Binding Contract
WCF Config File WCF Config File WCF Config File
Address String Binding Type WCF DLLs
Binding Instance Contract Type
No SecurityService Host Client Invocation
Address Binding Contract
WCF Config File WCF Config File Interface
Address String Binding Type
Binding Instance
DEMO
APPENDIX
Wording Intent
 Do... This standard or practice should be followed in all cases. If you think that your specific application
is exempt, it probably isn't.
 Do Not... This standard or practice should never be applied.
 You should... This standard or practice should be followed in most cases.
 You should not... This standard or practice should not be followed, unless there's reasonable justification.
 You can… This standard or practice can be followed if you want to; it's not necessarily good or bad. There
are probably implications to following the practice (dependencies, or constraints) that should be
considered before adopting it.
THANK YOU!

More Related Content

What's hot

WCF LOB SDK from CodeMastery
WCF LOB SDK from CodeMasteryWCF LOB SDK from CodeMastery
WCF LOB SDK from CodeMastery
clineer
 
Unlocking the Power of Salesforce Integrations with Confluent
Unlocking the Power of Salesforce Integrations with ConfluentUnlocking the Power of Salesforce Integrations with Confluent
Unlocking the Power of Salesforce Integrations with Confluent
AaronLieberman5
 
Being mean at hackathons
Being mean at hackathonsBeing mean at hackathons
Being mean at hackathons
Devang Paliwal
 

What's hot (20)

Wcf
Wcf Wcf
Wcf
 
Deep-dive into Microservice Outer Architecture
Deep-dive into Microservice Outer ArchitectureDeep-dive into Microservice Outer Architecture
Deep-dive into Microservice Outer Architecture
 
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
 
Introduction to Azure AppFabric
Introduction to Azure AppFabricIntroduction to Azure AppFabric
Introduction to Azure AppFabric
 
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
Consumer-driven contracts: avoid microservices integration hell! (LondonCD - ...
 
WCF LOB SDK at CNUG
WCF LOB SDK at CNUGWCF LOB SDK at CNUG
WCF LOB SDK at CNUG
 
WCF LOB SDK from CodeMastery
WCF LOB SDK from CodeMasteryWCF LOB SDK from CodeMastery
WCF LOB SDK from CodeMastery
 
Unlocking the Power of Salesforce Integrations with Confluent
Unlocking the Power of Salesforce Integrations with ConfluentUnlocking the Power of Salesforce Integrations with Confluent
Unlocking the Power of Salesforce Integrations with Confluent
 
Designing microservices platforms with nats
Designing microservices platforms with natsDesigning microservices platforms with nats
Designing microservices platforms with nats
 
Microservices
MicroservicesMicroservices
Microservices
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principles
 
Introducing Windows Azure BizTalk Services
Introducing Windows Azure BizTalk ServicesIntroducing Windows Azure BizTalk Services
Introducing Windows Azure BizTalk Services
 
"#Microfrontends #LowConnectivity #AsianMarket", Maxim Demidenko
"#Microfrontends #LowConnectivity #AsianMarket", Maxim Demidenko"#Microfrontends #LowConnectivity #AsianMarket", Maxim Demidenko
"#Microfrontends #LowConnectivity #AsianMarket", Maxim Demidenko
 
Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?Api Gateway - What's the use of an api gateway?
Api Gateway - What's the use of an api gateway?
 
Nats meetup sf 20150826
Nats meetup sf   20150826Nats meetup sf   20150826
Nats meetup sf 20150826
 
vodQA(Pune) 2018 - Consumer driven contract testing using pact
vodQA(Pune) 2018 - Consumer driven contract testing using pactvodQA(Pune) 2018 - Consumer driven contract testing using pact
vodQA(Pune) 2018 - Consumer driven contract testing using pact
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
 
Our way to microservices
Our way to microservicesOur way to microservices
Our way to microservices
 
Being mean at hackathons
Being mean at hackathonsBeing mean at hackathons
Being mean at hackathons
 
7. introduction
7. introduction7. introduction
7. introduction
 

Similar to Wcf best practice

MAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
MAX 2008: Build collaborative applications with Flex LCDS and CairngormMAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
MAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
Xavier Agnetti
 
Interoperability and Windows Communication Foundation (WCF) Overview
Interoperability and Windows Communication Foundation (WCF) OverviewInteroperability and Windows Communication Foundation (WCF) Overview
Interoperability and Windows Communication Foundation (WCF) Overview
Jorgen Thelin
 
Web services
Web servicesWeb services
Web services
aspnet123
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
Binu Bhasuran
 
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Jorgen Thelin
 
Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35
Subodh Pushpak
 

Similar to Wcf best practice (20)

Dynamics 365 Saturday - London 2018 - New Features and Deprecations with Dyna...
Dynamics 365 Saturday - London 2018 - New Features and Deprecations with Dyna...Dynamics 365 Saturday - London 2018 - New Features and Deprecations with Dyna...
Dynamics 365 Saturday - London 2018 - New Features and Deprecations with Dyna...
 
MAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
MAX 2008: Build collaborative applications with Flex LCDS and CairngormMAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
MAX 2008: Build collaborative applications with Flex LCDS and Cairngorm
 
WCF for begineers
WCF  for begineersWCF  for begineers
WCF for begineers
 
Jeffrey Richter
Jeffrey RichterJeffrey Richter
Jeffrey Richter
 
Day Of Cloud - Windows Azure Platform
Day Of Cloud - Windows Azure PlatformDay Of Cloud - Windows Azure Platform
Day Of Cloud - Windows Azure Platform
 
Interoperability and Windows Communication Foundation (WCF) Overview
Interoperability and Windows Communication Foundation (WCF) OverviewInteroperability and Windows Communication Foundation (WCF) Overview
Interoperability and Windows Communication Foundation (WCF) Overview
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
 
Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2 Applying Code Customizations to Magento 2
Applying Code Customizations to Magento 2
 
Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...
 
OMG CORBA Component Model tutorial
OMG CORBA Component Model tutorialOMG CORBA Component Model tutorial
OMG CORBA Component Model tutorial
 
Build Apps Using Dynamic Languages
Build Apps Using Dynamic LanguagesBuild Apps Using Dynamic Languages
Build Apps Using Dynamic Languages
 
Web services
Web servicesWeb services
Web services
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
 
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
 
Application integration framework & Adaptor ppt
Application integration framework & Adaptor pptApplication integration framework & Adaptor ppt
Application integration framework & Adaptor ppt
 
Understanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company indiaUnderstanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company india
 
Serhiy Kalinets "Embracing architectural challenges in the modern .NET world"
Serhiy Kalinets "Embracing architectural challenges in the modern .NET world"Serhiy Kalinets "Embracing architectural challenges in the modern .NET world"
Serhiy Kalinets "Embracing architectural challenges in the modern .NET world"
 
Nuno Godinho
Nuno GodinhoNuno Godinho
Nuno Godinho
 
Build Message-Based Web Services for SOA
Build Message-Based Web Services for SOABuild Message-Based Web Services for SOA
Build Message-Based Web Services for SOA
 
Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35
 

More from Yu GUAN

More from Yu GUAN (11)

Canada Chinese Microsoft Tech Club Event 1
Canada Chinese Microsoft Tech Club Event 1Canada Chinese Microsoft Tech Club Event 1
Canada Chinese Microsoft Tech Club Event 1
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03
 
You can git
You can gitYou can git
You can git
 
A Journey to Azure
A Journey to AzureA Journey to Azure
A Journey to Azure
 
Dream career dot NET
Dream career dot NETDream career dot NET
Dream career dot NET
 
NuGet package CI and CD
NuGet package CI and CDNuGet package CI and CD
NuGet package CI and CD
 
Hosting your own NuGet private repository
Hosting your own NuGet private repositoryHosting your own NuGet private repository
Hosting your own NuGet private repository
 
Windows service best practice
Windows service best practiceWindows service best practice
Windows service best practice
 
Unleash the power of code reuse - creating plugins for Xamarin
Unleash the power of code reuse - creating plugins for XamarinUnleash the power of code reuse - creating plugins for Xamarin
Unleash the power of code reuse - creating plugins for Xamarin
 
A Journey To Microsoft Azure E00 Azure 101
A Journey To Microsoft Azure E00 Azure 101A Journey To Microsoft Azure E00 Azure 101
A Journey To Microsoft Azure E00 Azure 101
 
Welcome to power point
Welcome to power pointWelcome to power point
Welcome to power point
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 

Wcf best practice

  • 1. WCF BEST PRACTICE Yu Guan | Microsoft MVP
  • 2. Meet Yu Guan | @askguanyu twitter.com/askguanyu linkedin.com/in/yuguan askguanyu.wordpress.com devlib.codeplex.com Microsoft MVP Speaker, Blogger, Hacker, Coder, Maker, Gamer Azure, IoT, Cross-platform Apps, GIS, Services
  • 3. WCF ARCHITECTURE GUIDELINE  Contract Segmentation  Parameters and Return Values  Data Mapping  Service Invocation  Service Granularity  Transferring Large Data Sets  Load Balancing
  • 4. Contract Segmentation   You should separate logically related interfaces, contracts, entities, messages, and enumerations into individual projects.   You should implement WCF Services as DLLs.
  • 5. Parameters and Return Values   You should mark your types with the DataContractAttribute and DataMemberAttribute attributes to create a data contract, which is the portion of the service contract that describes the data that your service operations exchange.   You should not use Out and Ref Parameters.   You should not use System.IO.Stream and derived types as parameter or return value.   You should not use System.IO.Stream and derived types inside of data contracts.
  • 6. Data Mapping   You should centralize your types into a common project in order to share the same data elements.   You should check Reuse types in referenced assemblies check box.
  • 7. Service Invocation   You should centralize your contracts into a separate project. The calling service can then reference these contract projects, which allows you to invoke the services without a proxy.
  • 8. Service Granularity   You should weigh the tradeoffs and benefits of many chatty calls versus a few chunky calls. Client Service 1 chatty calls Service 2 chunky calls
  • 9. Transferring Large Data Sets   You should consider using compressing when sending or receiving large data.   You can consider using streaming mode, but keep in mind that streaming mode has lots of restrictions
  • 10. Load Balancing No Security Transport Security Message Security
  • 11. DevLib.ServiceModel  NuGet: https://www.nuget.org/packages/DevLib.ServiceModel/  Source code: https://devlib.codeplex.com/SourceControl/latest#Main/Source/DevLib.ServiceM odel/ Address Binding Contract WCF Config File WCF Config File WCF Config File Address String Binding Type WCF DLLs Binding Instance Contract Type No SecurityService Host Client Invocation Address Binding Contract WCF Config File WCF Config File Interface Address String Binding Type Binding Instance
  • 12. DEMO
  • 13. APPENDIX Wording Intent  Do... This standard or practice should be followed in all cases. If you think that your specific application is exempt, it probably isn't.  Do Not... This standard or practice should never be applied.  You should... This standard or practice should be followed in most cases.  You should not... This standard or practice should not be followed, unless there's reasonable justification.  You can… This standard or practice can be followed if you want to; it's not necessarily good or bad. There are probably implications to following the practice (dependencies, or constraints) that should be considered before adopting it.

Editor's Notes

  1. A new WCF project contains an interface and an implementation. By default, the interface contains an OperationContract attribute and a DataContract attribute. These show you some of the options that you can include in your contracts. The service works correctly at the outset, but you often need to refactor it to accommodate your scenario. It is also probable that your project will require several different kinds of data elements. When inheriting from other service contract interfaces, you cannot override operation properties, such as the name or namespace. If you attempt to do so, you create a new operation in the current service contract. When you set up your project, there are several good practices to follow that will help you to organize your contracts and interfaces. These practices will also help you when you create unit tests, and to work with other services and their contracts. The first recommendation is to separate logically related interfaces, contracts, entities, messages, and enumerations into a separate project. One way to do this is to add a class library project to your solution and name it after your service name, with the word "Contract" appended to it. An example of this is Averna.BYOLT.WcfServiceLibrary1.Contract. The second recommendation is to organize your data contracts into separate folders and namespaces. Any data contract that is a type of request or response is logically considered a type of message and can be placed inside a folder named Messages. Any data contract that is an entity or that resembles a data transfer object (DTO), can be placed inside a folder named Entities. You can also separate enumerations into a folder called Enumerations. Good organization is important, especially when there are many contracts. After your code is organized, make sure that your namespaces reflect the folder name and path in which they are located. Another benefit to a logical organization is that it helps clarify what type of data contract you (or other developers) are referencing, whether from other projects or in unit tests. Organizing data contracts according to their type is a example of the PIE principle (Program Intently and Expressly). It is important to add names and namespaces to your DataContracts when you design contracts. This practice ensures that the proxy is generated correctly when your code relies on inheritance and generics. When you set up a solution in the Microsoft® Visual Studio® development system, logically organize your DataContracts into separate folders. Also, physically separate your contracts into a separate project. These organizational best practices help to maintain namespaces that are comprehensible, and makes it easy to reference your contracts from other projects. They also make unit testing easier. All the benefits of managed interfaces apply to service contract interfaces: Service contract interfaces can extend any number of other service contract interfaces. A single class can implement any number of service contracts by implementing those service contract interfaces. You can modify the implementation of a service contract by changing the interface implementation, while the service contract remains the same. You can version your service by implementing the old interface and the new one. Old clients connect to the original version, while newer clients can connect to the newer version. Implementing a WCF service as a DLL that is deployed to the \bin directory of a Web application allows you reuse the service outside of the Web application model, for example, in a test environment that may not have Internet Information Services (IIS) deployed.
  2. Each operation has a return value and a parameter, even if these are void. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects. This is significant because each type used in a parameter or return value must be serializable; that is, it must be possible to convert an object of that type into a stream of bytes and from a stream of bytes into an object. Primitive types are serializable by default, as are many types in the .NET Framework. Request/Reply A request/reply pattern is one in which a request sender (a client application) receives a reply with which the request is correlated. This is the default MEP because it supports an operation in which one or more parameters are passed to the operation and a return value is passed back to the caller. Note that unless you specify a different underlying message pattern, even service operations that return void (Nothing in Visual Basic) are request/reply message exchanges. The result for your operation is that unless a client invokes the operation asynchronously, the client stops processing until the return message is received, even though that message is empty in the normal case.  One-way If the client of a WCF service application should not wait for the operation to complete and does not process SOAP faults, the operation can specify a one-way message pattern. A one-way operation is one in which a client invokes an operation and continues processing after WCF writes the message to the network. Typically this means that unless the data being sent in the outbound message is extremely large the client continues running almost immediately (unless there is an error sending the data). This type of message exchange pattern supports event-like behavior from a client to a service application. A message exchange in which one message is sent and none are received cannot support a service operation that specifies a return value other than void; in this case an InvalidOperationException exception is thrown. No return message also means that there can be no SOAP fault returned to indicate any errors in processing or communication. (Communicating error information when operations are one-way operations requires a duplex message exchange pattern.) To specify a one-way message exchange for an operation that returns void, set the IsOneWay property to true. Out and Ref Parameters In most cases, you can use in parameters (ByVal in Visual Basic) and out and ref parameters (ByRef in Visual Basic). Because both out and ref parameters indicate that data is returned from an operation, an operation signature such as the following specifies that a request/reply operation is required even though the operation signature returns void. The only exceptions are those cases in which your signature has a particular structure. For example, you can use the NetMsmqBinding binding to communicate with clients only if the method used to declare an operation returns void; there can be no output value, whether it is a return value, ref, or out parameter. In addition, using out or ref parameters requires that the operation have an underlying response message to carry back the modified object. If your operation is a one-way operation, an InvalidOperationException exception is thrown at runtime. Other Operation Signature Requirements Some application features require a particular kind of operation signature. For example, the NetMsmqBinding binding supports durable services and clients, in which an application can restart in the middle of communication and pick up where it left off without missing any messages. (For more information, see Queues in Windows Communication Foundation.) However, durable operations must take only one in parameter and have no return value. Another example is the use of Stream types in operations. Because the Stream parameter includes the entire message body, if an input or an output (that is, ref parameter, out parameter, or return value) is of type Stream, then it must be the only input or output specified in your operation. In addition, the parameter or return type must be either Stream, System.ServiceModel.Channels.Message, or System.Xml.Serialization.IXmlSerializable. For more information about streams, see Large Data and Streaming. You should not be using System.IO.Stream derived types inside of data contracts. Stream data should be communicated using the streaming model, explained in the following "Streaming Data" section. Streaming Data When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. As mentioned earlier, enable streaming only for large messages (with text or binary content) if the data cannot be segmented, if the message must be delivered in a timely fashion, or if the data is not yet fully available when the transfer is initiated. Restrictions You cannot use a significant number of WCF features when streaming is enabled: Digital signatures for the message body cannot be performed because they require computing a hash over the entire message contents. With streaming, the content is not fully available when the message headers are constructed and sent and, therefore, a digital signature cannot be computed. Encryption depends on digital signatures to verify that the data has been reconstructed correctly. Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-of-sequence. Because of these functional constraints, you can use only transport-level security options for streaming and you cannot turn on reliable sessions. Streaming is only available with the following system-defined bindings: BasicHttpBinding NetTcpBinding NetNamedPipeBinding WebHttpBinding Because the underlying transports of NetTcpBinding and NetNamedPipeBinding have inherent reliable delivery and connection-based session support, unlike HTTP, these two bindings are only minimally affected by these constraints, in practice. Streaming is not available with the Message Queuing (MSMQ) transport and so cannot be used with the NetMsmqBinding or the MsmqIntegrationBinding class. The Message Queuing transport only supports buffered data transfers with a constrained message size, while all other transports do not have any practical message size limit for the vast majority of scenarios. Streaming is also not available when using the Peer Channel transport, so is not available with the NetPeerTcpBinding. Streaming and Sessions You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding and the service object's concurrency mode is set to single and its instance context mode is set to PerSession, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's Instance Context Mode to PerCall or Concurrency to Multiple. MaxConcurrentSessions has no effect in this case because there is only one "session" available.
  3. Data mapping between services can be cumbersome if there are interactions with several different services. If one service invokes another service, one or all of the data elements that have been passed to the first service may also need to be passed to the other services. An example of such a data element is a customer entity that is passed in from the client to an order service. Before the order can be processed, data is required from a shipping service, which, in turn, needs the same customer information as the order service. In this situation, many of the data elements that the order service needs are similar to the ones needed by the shipping service, and must be mapped. One possibility to consider when several services share the same data elements is to centralize your types into a common project. When you generate a proxy to one of the services, you can select the option to reuse types in referenced assemblies. This option can minimize the amount of data mapping that you must do when there are entities that are shared between services.
  4. It is important to manage invocations consistently when you invoke a service from a service. For example, if the service being invoked ends up in a faulted state, it is preferable to abort the channel rather than to close it, which can cause another exception. This is especially important if your WCF service is configured to run as a singleton, which means that one instance of the service is shared across all callers. Closing and aborting channels appropriately ensures that callers do not receive unexpected errors. Invocations Without Proxies If you control the services that interact with each other, you may want to centralize your contracts into a separate project. The calling service can then reference these contract projects, which allows you to invoke the services without a proxy. This means that there are no proxies to regenerate when you change a service. In other words, centralization can decrease development time, and prevent later problems with stale proxies. A drawback to this approach is that it blurs the separation between two layers. A proxy provides an operational boundary. It is a contract that the caller and the service have agreed to. No proxy eliminates some overhead, but introduces more coupling. Weigh the advantages and the tradeoffs in terms of your own situation.
  5. Service granularity presents a complex problem to designers of WCF services. The "divide and conqueror" approach is a common solution. It splits a service up into separate components that each performs operations that are the same or related. In addition, each service either can be designed to have several lightweight operations that will increase performance, or a few chunky operations that minimize the number of invocations. Chatty Services vs. Chunky Services Generally, services are designed to be either chatty or chunky. A chatty service returns data with a simple structure, and exposes many finely-grained operations. A chunky service defines coarse-grained operations, and returns data in a complex, hierarchal structure. To return the requested data, chatty services require more calls than chunky services do. However, chatty services allow the client to request only data that is relevant. Chunky services return larger data sets, much of which may be extraneous. In many cases, these large data sets can introduce latency into your service.
  6. WCF can process messages in one of two modes. By default, WCF processes messages in buffered mode. In buffered mode, WCF loads the entire message into memory before it is sent or after it is received. In other words, the entire message must be delivered before the receiver can read it. While buffered mode is efficient in most cases, buffering large data sets consumes large amounts of system resources, and the receiver must wait until it receives the entire message. This delay can cause performance issues on the server or the client. In streaming mode, the information is available to the receiver before the sender delivers the entire message. Streaming mode increases performance on very large data sets because they can be processed as they are received. Streaming is available on all standard bindings except for the NetMsmqBinding and the MsmqIntegrationBinding. If you stream large data sets, keep in mind that the service is constrained by the WCF default limits. You should increase the maxReceivedMessageSize value in your endpoint’s binding configuration.
  7. As distributed systems become more complex, the challenges of architecting a WCF system become greater. There are many issues to consider. A few of them are how to distribute network traffic, how to balance the server load, how to provide fault tolerance, and how to implement security. When many clients connect, the loads that are placed on WCF services increase. An important question is how to handle those times when the demand is heavy. A common approach is to implement a load balancer within the infrastructure. A load balancer takes incoming requests and distributes them among a number of servers that run the same service. A load balancer keeps a specific server from being overwhelmed with requests, which can significantly reduce the performance of the WCF service. When you implement a load balancer for WCF services, think about how to configure your bindings. Points to consider are: Should you use sticky or non-sticky sessions? What are the performance considerations? What are the security considerations? Infrastructure The purpose of a load balancer is to disperse traffic equally among several servers. The goal is to reduce the load on each server and continue to provide acceptable performance during periods of increased activity. The following illustration shows a commonly used implementation of a load balancer within an enterprise. The load balancer, whether it is a hardware appliance or the Windows Network Load Balancing Service (WNLBS), is within the firewall and sits between the external services and the company’s internal core services. In this example, the external services are services that accept connections from clients on the web. The external services are on several servers, and interact with the core services. The core services connect to the company’s internal databases in order to update and retrieve customer data, to process payments, to update inventory, and to initiate shipments. The load balancer that sits between the external and core services ensures that response times are acceptable. It monitors the load of each server and distributes the requests from the external services to the internal server(s) that are the least busy at that moment. Bindings It is just as important to ensure that a load-balanced WCF environment uses the proper binding as to implement the proper infrastructure. There are several binding options available for load balancing. See "Load Balancing" on MSDN at http://msdn.microsoft.com/en-us/library/ms730128.aspx for a complete list of these bindings. BasicHttpBinding The BasicHttpBinding is simple to implement, and works very well with existing HTTP load balancing techniques because the traffic is no different than other common types of web traffic. However, to avoid server affinity, you should disable the Keep-Alive value. To do this, implement a custom binding that sets the KeepAliveEnabled property to false. The MSDN topic “Load Balancing” mentioned previously, shows you how to configure the custom binding with KeepAliveEnabled specified. WSHttpBinding The WSHttpBinding provides a variety of security options. For example, the scenario shown in the previous illustration successfully distributes network traffic across several servers, and provides some fault tolerance if a server goes down. However, it does not secure the data as it is transported between the external and core Services. If you require secure sessions, one option is the WSHttpBinding. This binding provides transport security that protects the data as it travels between the external and core services, yet still maintains an acceptable level of performance. (In this scenario, acceptable performance is defined as sub-second response times, with the ability to handle a throughput of 100 requests per second, or more.) Transport security uses HTTPS to protect the data that is sent over the line. HTTPS prevents rogue users or programs within the network from reading the data. The WSHttpBinding also allows the load balancer to effectively route traffic to the core services. The following XML code is an example of how to configure the WSHttpBinding so that it provides transport security. <bindings> <wsHttpBinding> <binding name="MyServiceBinding"> <security mode="Transport"> <transport clientCredentialType="None" ></transport> </security> </binding> </wsHttpBinding> </bindings> Establishing Security Context The previous example showed how to implement transport security. You can also provide security at the message level by: Enabling sticky sessions or Setting the establishSecurityContext property to false. Enabling sticky sessions is beyond the scope of this article. Most hardware and software load balancers have this feature. Once a client establishes a session to the server, a sticky session will ensure subsequent requests from the client will route to the same server every time. This is often referred to as server affinity. If you are using Windows Server 2008, you have the option to user the Network Load Balancing feature. For more information refer to http://technet.microsoft.com/en-us/library/cc732855(WS.10).aspx. In this scenario, sticky sessions must be enabled on the load balancer. Enabling sticky sessions prevents errors that can occur when the system is under high load. If sticky sessions are not enabled, and the establishSecurityContext property of the WSHttpBinding is set to true or it is not specified, it is possible to receive a System.ServiceModel.FaultException. This error means that the security context token is either expired or is invalid, and the message was not processed. When a security session is established between servers, there is a one-time initial step that exchanges asymmetrically encrypted messages. Subsequent requests use this established session and messages are symmetrically encrypted. It is possible that one of these subsequent requests is routed to a server that is not a part of the established session. This causes a FaultException to occur. If the establishSecurityContext property is set to false, the one-time initial step is not executed, and requests do not rely on an established session. This is the alternative to using sticky sessions. The following XML code shows how to set the establishSecurityContext property to false. <bindings> <wsHttpBinding> <binding name=”MyServiceBinding”> <security mode=”Message” > <message establishSecurityContext=”false” clientCredentialType=”Windows” /> </security> </binding> </wsHttpBinding> </bindings> How the establishSecurityContext property is set impacts performance. To determine how to configure this property, you must first understand how the client invokes the service. If the client invokes the service and then disconnects, performance is better with establishSecurityContext set to false because symmetric encryption is much faster than asymmetric encryption. On the other hand, if the client invokes the service and calls several methods, performance is better with establishSecurityContext set to true. NetTcpBinding The NetTcpBinding provides better performance than either BasicHttpBinding or WSHttpBinding do. However, load balancing is more challenging to implement because the NetTcpBinding pools TCP connections by default. This binding ensures that clients remain sticky to the same server. You can use the NetTcpBinding in the same scenario that used WSHttpBinding, if you implement it with a few changes. Because clients have affinity to the server associated with their channel, application code should include try-again logic in case the server fails. This logic ensures that the client is routed to a server that is up and responsive. When you choose a binding, think about sticky sessions, performance, and security considerations. Production scenarios vary, but they often require you to have one or more load balancers. Take this into account as you design your service-oriented architecture.