www.it-ebooks.info
www.it-ebooks.info
4TH EDITION
Programming WCF Services
Juval Lowy & Michael Montgomery
Boston
www.it-ebooks.info
Programming WCF Services
by Juval Lowy and Michael Montgomery
Copyright © 2016 Juval Lowy and Michael Montgomery. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (). For more information, contact our corporate/
institutional sales department: 800-998-9938 or
Editors: Brian MacDonald and Rachel Roumeliotis
Production Editor: Melanie Yarbrough
Proofreader: Jasmine Kwityn
Indexer: WordCo Indexing Services
December 2015:
Interior Designer: David Futato
Cover Designer: Randy Comer
Illustrator: Rebecca Demarest
Fourth Edition
Revision History for the Fourth Edition
2015-11-04: First Release
See for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming WCF Services, the cover
image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-94483-7
[LSI]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. WCF Essentials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Is WCF?
Services
Service Execution Boundaries
WCF and Location Transparency
Addresses
TCP Addresses
HTTP Addresses
IPC Addresses
MSMQ Addresses
WebSocket Addresses
UDP Addresses
Contracts
The Service Contract
Hosting
IIS Hosting
Self-Hosting
WAS Hosting
Custom Hosting in IIS/WAS
Choosing a Host
Bindings
The Common Bindings
Choosing a Binding
Additional Bindings
Using a Binding
Endpoints
1
3
4
5
5
6
7
7
8
8
8
8
9
13
14
15
21
21
22
23
24
26
27
30
30
iii
www.it-ebooks.info
Administrative Endpoint Configuration
Programmatic Endpoint Configuration
Default Endpoints
The Configure() Method
Metadata Exchange
Metadata over HTTP-GET
The Metadata Exchange Endpoint
The Metadata Explorer
More on Behavior Configuration
Client-Side Programming
Generating the Proxy
Administrative Client Configuration
Programmatic Client Configuration
The WCF-Provided Test Client
Programmatic Versus Administrative Configuration
Configuration Policy
WCF Architecture
Host Architecture
Working with Channels
The InProcFactory Class
Transport-Level Sessions
Transport Session and Binding
Transport Session Termination
Reliability
Bindings, Reliability, and Ordered Messages
Configuring Reliability
Requiring Ordered Delivery
31
35
37
40
43
44
47
54
56
58
59
64
71
72
75
75
76
77
78
80
84
84
85
86
87
88
89
2. Service Contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Operation Overloading
Contract Inheritance
Client-Side Contract Hierarchy
Service Contract Factoring and Design
Contract Factoring
Factoring Metrics
Contract Queries
Programmatic Metadata Processing
The MetadataHelper Class
93
96
97
101
101
103
105
106
109
3. Data Contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Serialization
.NET Serialization
iv
|
115
117
Table of Contents
www.it-ebooks.info
The WCF Formatters
Data Contract via Serialization
Data Contract Attributes
Importing a Data Contract
Data Contracts and the Serializable Attribute
Inferred Data Contracts
Composite Data Contracts
Data Contract Events
Shared Data Contracts
Data Contract Hierarchy
Known Types
Service Known Types
Multiple Known Types
Configuring Known Types
Data Contract Resolvers
Objects and Interfaces
Data Contract Equivalence
Serialization Order
Versioning
New Members
Missing Members
Versioning Round-Trip
Data Contract Factoring and Design
Data Contract Design
Data Contract Factoring
Operation Factoring
The Data Transfer Object Pattern
Enumerations
Delegates and Data Contracts
Generics
Collections
Concrete Collections
Custom Collections
The CollectionDataContract Attribute
Referencing a Collection
Dictionaries
119
122
123
125
129
130
131
133
136
137
138
140
141
142
143
155
157
158
160
161
162
166
169
169
169
181
183
184
186
187
191
192
194
194
196
196
4. Instance Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Behaviors
Per-Call Services
Benefits of Per-Call Services
Configuring Per-Call Services
201
203
204
204
Table of Contents
www.it-ebooks.info
|
v
Per-Call Services and Transport Sessions
Designing Per-Call Services
Choosing Per-Call Services
Per-Session Services
Configuring Private Sessions
Sessions and Reliability
The Session ID
Session Termination
Singleton Service
Initializing a Singleton
Choosing a Singleton
Demarcating Operations
Instance Deactivation
Configuring with ReleaseInstanceMode.None
Configuring with ReleaseInstanceMode.BeforeCall
Configuring with ReleaseInstanceMode.AfterCall
Configuring with ReleaseInstanceMode.BeforeAndAfterCall
Explicit Deactivation
Using Instance Deactivation
Durable Services
Durable Services and Instance Management Modes
Instance IDs and Durable Storage
Explicit Instance IDs
Instance IDs in Headers
Context Bindings for Instance IDs
Automatic Durable Behavior
Throttling
Configuring Throttling
206
206
209
209
210
215
216
218
218
220
223
223
226
227
228
229
229
230
231
231
232
233
234
236
239
245
252
255
5. Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Request-Reply Operations
One-Way Operations
Configuring One-Way Operations
One-Way Operations and Reliability
One-Way Operations and Sessionful Services
One-Way Operations and Exceptions
Callback Operations
The Callback Contract
Client Callback Setup
Service-Side Callback Invocation
Callback Connection Management
The Duplex Proxy and Type Safety
vi
|
Table of Contents
www.it-ebooks.info
261
262
262
263
263
264
266
267
268
272
275
278
The Duplex Factory
Callback Contract Hierarchy
Events
Streaming
I/O Streams
Streaming and Binding
Streaming and Transport
281
283
285
289
289
290
291
6. Faults. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Error Isolation and Decoupling
Error Masking
Channel Faulting
Fault Propagation
Fault Contracts
Fault Debugging
Faults and Callbacks
Error-Handling Extensions
Providing a Fault
Handling a Fault
Installing Error-Handling Extensions
The Host and Error Extensions
Callbacks and Error Extensions
293
294
295
299
301
305
312
315
316
319
322
325
329
7. Transactions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
The Recovery Challenge
Transactions
Transactional Resources
Transaction Properties
Transaction Management
Resource Managers
Transaction Propagation
Transaction Flow and Bindings
Transaction Flow and the Operation Contract
One-Way Calls
Transaction Protocols and Managers
Protocols and Bindings
Transaction Managers
Transaction Manager Promotion
The Transaction Class
The Ambient Transaction
Local Versus Distributed Transactions
Transactional Service Programming
333
334
335
335
337
341
341
341
343
345
345
346
348
350
352
352
353
354
Table of Contents
www.it-ebooks.info
|
vii
Setting the Ambient Transaction
Transaction Propagation Modes
Voting and Completion
Transaction Isolation
Transaction Timeout
Explicit Transaction Programming
The TransactionScope Class
Transaction Flow Management
Non-Service Clients
Service State Management
The Transaction Boundary
Instance Management and Transactions
Per-Call Transactional Services
Per-Session Transactional Services
Transactional Durable Services
Transactional Behavior
Transactional Singleton Service
Instancing Modes and Transactions
Callbacks
Callback Transaction Modes
Callback Voting
Using Transactional Callbacks
354
357
365
369
371
373
373
375
383
384
385
386
387
391
406
408
415
418
419
420
422
422
8. Concurrency Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Instance Management and Concurrency
Service Concurrency Modes
ConcurrencyMode.Single
ConcurrencyMode.Multiple
ConcurrencyMode.Reentrant
Instances and Concurrent Access
Per-Call Services
Sessionful and Singleton Services
Resources and Services
Deadlocked Access
Deadlock Avoidance
Resource Synchronization Context
.NET Synchronization Contexts
The UI Synchronization Context
Service Synchronization Context
Hosting on the UI Thread
A Form as a Service
The UI Thread and Concurrency Management
viii
| Table of Contents
www.it-ebooks.info
428
428
429
429
433
436
436
437
438
438
439
441
441
445
451
452
458
461
Custom Service Synchronization Contexts
The Thread Pool Synchronizer
Replacing the I/O Completion Thread Pool
Thread Affinity
Priority Processing
Callbacks and Client Safety
Callbacks with ConcurrencyMode.Single
Callbacks with ConcurrencyMode.Multiple
Callbacks with ConcurrencyMode.Reentrant
Callbacks and Synchronization Contexts
Callbacks and the UI Synchronization Context
Callback Custom Synchronization Contexts
Asynchronous Calls
Requirements for an Asynchronous Mechanism
Proxy-Based Asynchronous Calls
Asynchronous Invocation
Polling or Waiting for Completion
Continuations
One-Way Asynchronous Operations
Asynchronous Error Handling
Asynchronous Calls and Transactions
Synchronous Versus Asynchronous Calls
Asynchronous Service Operations
464
464
469
471
473
477
478
479
479
480
480
484
488
488
489
492
494
497
508
512
515
516
517
9. Queued Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Disconnected Services and Clients
Queued Calls
Queued Calls Architecture
Queued Contracts
Configuration and Setup
Transactions
Delivery and Playback
Service Transaction Configuration
Nontransactional Queues
Instance Management
Per-Call Queued Services
Sessionful Queued Services
Singleton Service
Concurrency Management
Throttling
Delivery Failures
The Dead-Letter Queue
543
544
545
545
546
554
554
556
559
560
561
563
566
567
568
569
570
Table of Contents
www.it-ebooks.info
|
ix
Time to Live
Configuring the Dead-Letter Queue
Processing the Dead-Letter Queue
Playback Failures
Poison Messages
Poison Message Handling
Queued Versus Connected Calls
Requiring Queuing
The Response Service
Designing a Response Service Contract
Client-Side Programming
Queued Service-Side Programming
Response Service-Side Programming
Transactions
The HTTP Bridge
Designing the Bridge
Transaction Configuration
Service-Side Configuration
Client-Side Configuration
571
571
573
578
579
579
584
586
587
588
592
595
597
598
602
602
603
604
606
10. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Authentication
Authorization
Transfer Security
Transfer Security Modes
Transfer Security Mode Configuration
Transport Security and Credentials
Message Security and Credentials
Identity Management
Overall Policy
Scenario-Driven Approach
Intranet Application Scenario
Securing the Intranet Bindings
Constraining Message Protection
Authentication
Identities
The Security Call Context
Impersonation
Authorization
Identity Management
Callbacks
Internet Application Scenario
x
|
Table of Contents
www.it-ebooks.info
609
610
611
612
614
617
617
618
618
619
620
620
628
629
632
633
635
643
650
651
652
Securing the Internet Bindings
Message Protection
Authentication
Using Windows Credentials
Using the ASP.NET Providers
Identity Management
Business-to-Business Application Scenario
Securing the Business-to-Business Bindings
Authentication
Authorization
Identity Management
Host Security Configuration
Anonymous Application Scenario
Securing the Anonymous Bindings
Authentication
Authorization
Identity Management
Callbacks
No Security Scenario
Unsecuring the Bindings
Authentication
Authorization
Identity Management
Callbacks
Scenarios Summary
Declarative Security Framework
The SecurityBehaviorAttribute
Host-Side Declarative Security
Client-Side Declarative Security
Security Auditing
Configuring Security Audits
Declarative Security Auditing
652
655
660
662
663
673
673
674
674
677
679
679
680
680
681
681
681
682
682
682
683
683
683
683
684
684
685
693
695
702
703
706
11. The Azure Service Fabric. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
Why Azure Service Fabric
An Integrated Platform
Design Consistency
Programming Model Consistency
Future Compatible
Preparing for the Service Fabric
ServiceModelEx.ServiceFabric
Configuring the Service Fabric
709
710
710
711
711
713
713
714
Table of Contents
www.it-ebooks.info
|
xi
IT Operations
Development
Both
Programming the Service Fabric
The Service Programming Model
Reliable Services
Reliable Actors
State Management
Hosting
The Client Programming Model
Modeling the Service Fabric
Modeling Approach
Modeling Reliable Services
Modeling Reliable Actors
Modeling Hosting
Testing
714
716
718
723
724
724
734
737
745
746
756
757
758
761
770
771
A. Introduction to Service Orientation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
B. Headers and Contexts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
C. Discovery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
D. Publish-Subscribe Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883
E. Generic Interceptor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
F. WCF Coding Standard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
G. ServiceModelEx Catalog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 969
xii
|
Table of Contents
www.it-ebooks.info
Preface
On the software time scale, WCF is ancient. In August 2001, I first learned the details
of a Microsoft effort to rewrite COM+ using managed code. Nothing much happened
after that. Then, during a C# 2.0 Strategic Design Review in July 2002, the remoting
program manager outlined in broad strokes plans to rework remoting into something
that developers should actually use. At the same time, Microsoft was also working on
incorporating the new security specs for web services into the ASMX stack and
actively working with others on drafting a score of additional web services specs.
In July 2003, I was given access to a new transactional infrastructure that improved
on the deficiencies in transactional .NET programming. At the time, there was no
cohesive programming model that unified these distinct technologies. Toward the
end of 2003, I was privileged to be invited to join a small team of outside industry
experts and to participate in the strategic design review of a new development plat‐
form codenamed Indigo. Some of the smartest and nicest people I ever worked with
were part of that team. Over the next two to three years, Indigo went through some
three generations of programming models. The final declarative, endpoint-driven
object model debuted in early 2005, was stabilized by August of that year, and was
named the Windows Communication Foundation (WCF). WCF was released in
November 2006 as part of .NET 3.0
On the software relevancy scale, WCF is a titan. It has all the correct elements
required to build a modern software system including the foundational pattern of all
modern software; an extensible, interception-based pipeline. It is the basis for the
upcoming Azure Service Fabric and it integrates with the Service Fabric as-is. In fact,
the previous three editions of this book showed how to implement all the elements of
the Service Fabric already. As such, WCF is as paramount as ever.
WCF has several facets, and is the only technology today that offers interoperability,
productivity and extensibility. It is the ultimate interoperability solution, an imple‐
mentation of a long list of industry standards. To the distributed application devel‐
oper, it is the easiest way of making remote calls and even queued calls. To the system
xiii
www.it-ebooks.info
developer, it is the next generation of productivity-oriented features, such as transac‐
tions and hosting, that provide off-the-shelf plumbing for applications. To the appli‐
cation developer, it is a declarative programming model for structuring applications.
And to the architect, it is a tool for building service-oriented applications. WCF is, in
actuality, all of those, simply because it was designed that way—to be the unified
offering of Microsoft’s disparate technologies.
To me, WCF is a superior development platform, which to a large extent subsumed
raw .NET programming. All .NET developers should use WCF, regardless of their
application types, sizes, or industry domains. WCF is a fundamental technology that
provides an easy and clean way to generate services and applications in compliance
with what I regard as sound design principles. WCF was engineered from the ground
up to simplify application development and deployment and to lower the overall cost
of ownership. WCF services allow you to build service-oriented applications, from
standalone desktop applications to web-based applications and services to high-end
Enterprise applications.
How This Book Is Organized
This book covers the topics and skills you need to design and develop serviceoriented WCF-based applications, illustrating how to take advantage of built-in fea‐
tures such as service hosting, instance management, concurrency management,
transactions, disconnected queued calls, security, and the new Windows Azure Ser‐
vice Fabric. But in fact, this book is not about WCF. It is about modern software engi‐
neering, using WCF as a medium to express these design ideas. The various concepts
disused in this book transcend technologies. So while the book shows you how to use
these features in WCF, it focuses on the “why” and on the rationale behind particular
design decisions. You’ll learn about not only WCF programming and the related sys‐
tem issues, but also relevant design options, tips, best practices, and pitfalls. I
approach almost every topic and aspect from a software engineering standpoint,
because my objective is to make you not just a WCF expert, but also a better software
engineer. Armed with the insights this text provides, you can engineer your applica‐
tions for maintainability, extensibility, reusability, and productivity.
This fourth edition has provided me with several opportunities: first, to catch up with
WCF in .NET 4.6 with its new features of parallel processing and configuration. Sec‐
ond, I wanted to present the upcoming Azure Service Fabric, which is a fundamen‐
tally disruptive technology because of the sort of applications it allows developers to
build and how it unifies development and operations. Third, I have had a few more
years’ worth of WCF techniques, ideas, and helper classes, as well as improvement of
the ideas I had in the previous editions. I believe this new material will make this edi‐
tion valuable even to readers of the third edition.
xiv
|
Preface
www.it-ebooks.info
This book avoids many implementation details of WCF and largely confines its cov‐
erage to the possibilities and practical aspects of using WCF: how to apply the tech‐
nology and how to choose among the available design and programming models. It
makes the most of what .NET 4.6 and the Service Fabric has to offer, and in some
respects is an advanced C# book as well.
In addition, the book contains many useful utilities, tools, and helper classes I have
written, collectively known as ServiceModelEx. My tools, helper classes, and attributes
aim at increasing your productivity and the quality of your WCF services. ServiceMo‐
delEx is literally a small framework that sits on top of WCF and compensates for
some oversights in its design. ServiceModelEx also simplifies and automates certain
tasks. This book is as much about my tools, ideas, and techniques as it is about native
WCF, and my framework also demonstrates how you can extend WCF. Many readers
have told me that aside from the explanations in this book, ServiceModelEx is the
most valuable asset the book offers. I have also kept to my guideline that, in principle,
readers should not have to use all (or any part) of ServiceModelEx. In practice, Serv‐
iceModelEx is your WCF power tools collection. You can also use each helper class,
utility, or framework individually, as there are few, if any, interdependencies.
Each chapter addresses a single topic and discusses it in depth. However, the chapters
often rely on those that precede them, so you should read the book in order.
Here is a brief summary of the chapters and appendixes in this book:
Chapter 1, WCF Essentials
This first chapter starts by explaining what WCF is, then describes essential WCF
concepts and building blocks (such as addresses, contracts, bindings, endpoints,
hosting, and clients) and key concepts such as reliability and transport sessions.
The chapter includes a discussion of the WCF architecture, which is really the
linchpin of all that follows in the subsequent chapters. This chapter assumes that
you understand the basic motivation and benefit of service orientation. If that is
not the case, you should first read Appendix A. Even if you are already familiar
with the basic concepts of WCF, I recommend that you give this chapter at least a
cursory reading, not only to ensure that you have a solid foundation, but also
because some of the helper classes and terms introduced here will be used and
extended throughout the book.
Chapter 2, Service Contracts
Chapter 2 is dedicated to the topic of designing and working with service con‐
tracts. First, it covers some useful techniques for service contract overloading and
inheritance, as well as some advanced techniques. The chapter also discusses how
to design and factor contracts that cater to reuse, maintainability, and extensibil‐
ity. It ends by showing you how to interact programmatically with the metadata
of the exposed contracts at runtime.
Preface
www.it-ebooks.info
|
xv
Chapter 3, Data Contracts
Chapter 3 deals with how the client and the service can exchange data without
ever actually sharing the data type itself or using the same development technol‐
ogy. In this chapter, you will see how to deal with some interesting real-life issues,
such as data versioning, and how to pass collections of items. This chapter also
extends the contract design and factoring discussion of Chapter 2 to data con‐
tracts.
Chapter 4, Instance Management
This chapter answers the question of which service instance handles which cli‐
ent’s request. WCF supports several service instance management, activation, and
lifetime management techniques, and your choices will have drastic implications
for scalability, performance, the programming model, and the business workflow.
This chapter presents the rationale behind each of the instance management
modes, offers guidelines on when and how to best use them, and also addresses
some related topics, such as durability and throttling.
Chapter 5, Operations
Chapter 5 deals with the types of operations clients can invoke on a service and
related design guidelines, such as how to improve on and extend the basic WCF
offering to support callback setup and teardown, manage callback ports and
channels, and provide for type-safe duplex proxies.
Chapter 6, Faults
This chapter discusses the best practices of error handling, enabling you to
decouple the client’s error handling from the service’s. When required, the chap‐
ter shows how services can report errors and exceptions back to their clients,
since constructs such as exceptions and exception handling are technologyspecific and should not transcend the service boundary. This chapter also dem‐
onstrates how you can extend and improve on WCF’s basic error-handling
mechanism.
Chapter 7, Transactions
This chapter begins by explaining the motivation for transactions in general,
then discusses the many aspects of transactional services: the transaction man‐
agement architecture, transaction propagation configuration, the declarative
transaction support offered by WCF, and how clients can create transactions. The
chapter ends by discussing relevant design guidelines such as transactional ser‐
vice state management and instancing modes.
Chapter 8, Concurrency Management
Chapter 8 first describes the powerful yet simple declarative way WCF offers for
managing concurrency and synchronization, both for the client and the service.
The chapter then presents more advanced aspects of concurrency management,
xvi
|
Preface
www.it-ebooks.info
such as callbacks, reentrancy, thread affinity, and synchronization context, best
practices and guidelines for avoiding deadlocks, and asynchronous call manage‐
ment. The chapter also explores the Task-based Asynchronous Pattern (TAP) and
how this style of asynchrony relates to WCF, highlighting best practice techni‐
ques, as well as, discussing potential pitfalls.
Chapter 9, Queued Services
Chapter 9 shows how clients can queue up calls to services, thus enabling asyn‐
chronous, disconnected work. The chapter starts by showing how to set up and
configure queued services, then focuses on aspects such as transactions, instance
management, and failures and their impact on both the business model of the
service and its implementation. It also presents techniques for streamlining
queues, call management, and several original design ideas (such as a queued
response service).
Chapter 10, Security
This chapter demystifies service-oriented security by breaking down this multi‐
faceted task into its basic elements, such as message transfer, authentication, and
authorization. It also demonstrates how to provide security for key scenarios
such as intranet and Internet applications. Finally, it presents my framework for
declarative WCF security, designed to automate security setup and to considera‐
bly simplify managing security.
Chapter 11, The Azure Service Fabric
Chapter 11 introduces you to the Azure Service Fabric. This chapter starts by
briefly explaining the value and rationale behind the new platform and continues
by presenting the Service Fabric’s many capabilities. The chapter ends by present‐
ing ServiceModelEx.ServiceFabric, our operational Service Fabric that simpli‐
fies how you prepare for the Service Fabric and allows you to deploy Service
Fabric code to any Windows environment that can host WCF services.
Appendix A, Introduction to Service Orientation
This appendix is designed for readers who want to understand what service ori‐
entation is all about: it presents my take on service orientation and puts it in a
concrete context. The appendix defines service-oriented applications (as opposed
to mere architecture) and the services themselves and examines the benefits of
the methodology. It then presents the principles of service orientation and aug‐
ments the abstract tenets with a few more practical points required by most
applications. In this appendix, I also share my perspective on where SOA and
WCF are heading.
Appendix B, Headers and Contexts
This appendix introduces two distinct techniques for enabling the client to pass
out-of-band parameters to the service, resulting in a custom logical context: you
Preface
www.it-ebooks.info
|
xvii
will see how to use either the message headers or the context binding to achieve
this goal. This appendix also presents my helper classes, which greatly simplify
and encapsulate the required programming. These helper classes and custom
contexts are used in several places in the book.
Appendix C, Discovery
This appendix starts by describing the basic offering of service discovery and
availability announcements introduced in .NET 4.0. Discovery simplifies service
and client deployment and management, and allows for great volatility across
time and deployment sites. The appendix then shows some simple techniques
and helper classes you can use to streamline the programming model. The
appendix ends with our technique for TCP-based discovery that mimics regular
WCF discovery, benefiting from discovery even where UDP is disallowed.
Appendix D, Publish-Subscribe Service
Appendix D presents several techniques for implementing a publish-subscribe
event management solution. It starts with my framework, which lets you develop
a publishing and a subscription service in, at most, one line of code. The appen‐
dix ends with a discovery-enabled publish-subscribe solution that requires no
explicit subscriptions steps.
Appendix E, Generic Interceptor
This appendix presents a general-purpose extensible framework for intercepting
calls to your WCF services. It walks through the technique and thought process
behind such an extension and shows two examples of how to utilize this simple
yet powerful and useful technique.
Appendix F, WCF Coding Standard
Appendix F is basically a consolidated list of all the best practices and dos and
don’ts mentioned throughout this book. The standard is all about the “how” and
the “what,” not the “why.” The rationale behind it is found in the rest of the book.
The standard also uses the terms and helper classes discussed in this book.
Appendix G, ServiceModelEx Catalog
The final appendix presents a catalog of the 100 or so public helper types (exclud‐
ing internal helper types) of ServiceModelEx mentioned in the book, arranged by
categories and techniques, with a short description of each.
Introducing Michael “Monty” Montgomery
In 2009 at my annual Architect’s Master Class I met Monty, who at the time was the
chief architect of a large enterprise. Over the next few years we kept in touch since
Monty was one of the best architects I have ever met. Monty has a natural knack for
service-oriented design and the related system issues. He also proved to be a WCF
expert. In 2012 he finally made the jump and joined IDesign. The reason I wanted
xviii
|
Preface
www.it-ebooks.info
him had almost nothing to do with his technical expertise. Monty has a fundamental
appreciation for what it takes to make a developer team of a broad spectrum of acu‐
men productive. Over the years Monty has mentored many architects on how to ach‐
ieve just that objective, so he was a natural fit to help with this fourth edition of the
WCF ‘Bible’. Together we bounced new and old ideas off each other, culminating in
the new techniques you read in this book.
With the addition of a second author, I wanted to keep the original author’s voice
from the previous three editions when referring to personal opinions or contribu‐
tions. As with the previous editions, when the text mentions “I” or “my,” it refers to
Juval. When it says “we” or “our,” it refers to both Juval and Monty.
Some Assumptions About the Reader
I assume that you, the reader, are an experienced developer and that you are comfort‐
able with object-oriented concepts such as encapsulation and inheritance. I will take
advantage of your existing understanding of object and component technology and
terminology, and port that knowledge to WCF. You should ideally have a fair under‐
standing of .NET and know C# 4.5. Although the book uses C# for the most part, it is
just as pertinent to Visual Basic developers.
What You Need to Use This Book
To use this book, you will need .NET 4.5 or .NET 4.6 and Visual Studio 2015 or 2016.
For the Service Fabric appendix, you will need the Windows Azure Service Fabric
SDK. Unless I explicitly mention otherwise, the contents apply to any platform that
can run WCF. You may also install additional Windows components, such as MSMQ
and IIS.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Used for technical terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for code samples, statements, namespaces, classes, assemblies, interface
directives, operators, attributes, and reserved words.
Constant width bold
Used for emphasis in code samples.
Preface
www.it-ebooks.info
|
xix
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Whenever I wish to make a point in a code sample, I do so with the static Assert
method of the Debug class:
int number = 1+2;
Debug.Assert(number = 3);
The Assert method accepts a Boolean value and throws an exception when it is false.
The book follows the recommended naming guidelines and coding style available at
iDesign. Whenever it deviates from that standard, it is likely the result of space or
line-length constraints. As for naming conventions, I use “Pascal casing” for public
member methods and properties; this means the first letter of each word in the name
is capitalized. For local variables and method parameters I use “camel casing,” in
which the first letter of each word in the name is capitalized, with the exception of the
first word. The names of private member variables are prefixed with m_:
class SomeClass
{
int m_Number;
public int Number
{get;set};
}
I use ellipses between curly braces to indicate the presence of code that is necessary
but unspecified:
xx
|
Preface
www.it-ebooks.info
class SomeClass
{...}
In the interest of clarity and space, code examples often do not contain all the using
statements needed to specify all the namespaces the examples require; instead, such
examples include only the new namespaces introduced in the preceding text.
Safari® Books Online
Safari Books Online is an on-demand digital library that deliv‐
ers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at />You can also contact the author at: .
The author has posted a comprehensive code library on the IDesign website with
more than 150 downloads related to WCF essentials, contract design, instance man‐
Preface
www.it-ebooks.info
|
xxi
agement, operations and calls, faults, transactions, concurrency, queuing, security,
and the service bus. The downloads articulate many of the code snippets in this book
in a working fashion. However, because of the large number of the downloads, the
maintenance involved, and the fact that these secondary, accompanying examples do
not themselves appear in the book, they are provided separately from the official
sources.
To comment or ask technical questions about this book, send email to bookques‐
For more information about our books, courses, conferences, and news, see our web‐
site at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />
Acknowledgments
I would not have been able to come to terms with WCF in its early days without the
constant support of and interaction with the WCF (then Indigo) program managers. I
am especially grateful to Steve Swartz, one of the WCF architects, not just for his
knowledge and insight, but also for his patience with me and those long IM sessions.
Thanks go to Yasser Shohoud, Doug Purdy, and Shy Cohen for the fascinating strate‐
gic design reviews and to Krish Srinivasan for his almost philosophical approach to
engineering. Working with you guys has been the best part of learning WCF and a
privilege in its own right. The following WCF program managers also shared their
time and helped clarify WCF: Andy Milligan, Brian McNamara, Eugene Osovetsky,
Kenny Wolf, Kirill Gavrylyuk, Max Feingold, Michael Marucheck, Mike Vernal, and
Steve Millet. Thanks also to the group manager, Angela Mills.
Outside Microsoft, I am grateful to Nicholas Paldino for his help. This is the sixth
book that Nick has reviewed for me, and by now I am hooked. I simply cannot imag‐
ine going to print without Nick’s insight, meticulous scrutiny, and diligent help, to say
nothing about Nick’s technical competence, which is nothing short of awe-striking
and humbling. The books are always a superior product as a result of his editing and
feedback.
I dedicate the book to the IDesign Alumni. A unique post-class benefit of attending
one of the IDesign Master Classes is joining this private forum where you can discuss
practicing our techniques, share observation and insights, and ask pertinent ques‐
tions. The members of the forum are all world-class developers, architects, and
project leads, and the discussion amongst this group is profound, insightful, and of
the highest quality. Many of the ideas and techniques in this book were first tried on
xxii
|
Preface
www.it-ebooks.info
and trialed by the fire of the Alumni. The best emails I get each day are the discussion
of the Alumni forum, and the level of mutual involvement, empathy, excellence, pro‐
fessional integrity and responsiveness is second to none. It is truly inspiring that a
community of mostly virtual peers can care about their trade and each other that
much. I thank you for every time you made us stop and think about the best way of
answering a question, a smarter way of solving an Alumni’s design problem, or the
need for an improved technique. It is people like you that we write books for.
Preface
www.it-ebooks.info
|
xxiii