Tải bản đầy đủ
Objective 3.2: Configure WCF Services by using configuration settings

Objective 3.2: Configure WCF Services by using configuration settings

Tải bản đầy đủ

Here’s a quick example to illustrate this assertion. Assume that you have a WCF Service
that’s hosted in a Managed Windows Service and it currently uses the basicHttpBinding. You
want to either add or change support to employ a wsHttpBinding. If you have the binding configured as opposed to defined in the code, all that’s needed is a quick change to the
.configuration file. The service doesn’t need to be changed, it doesn’t need redeployed, and it
doesn’t need anything else done to it (other than maybe restarted).
Similarly, suppose that a problem crops up, and you want to enable some diagnostics
to help discern what the problem is. If you’re using configuration, this can be done without
touching a line of .NET code and without modifying the service. You can enable the diagnostics you want, let it run for a period long enough to get a feel for the problem, and then
turn it off, all without changing the service. If you use the code-centric approach, you have to
engage in a new version to add the diagnostic code and then another rollback to undo it. Virtually every aspect of the service’s or client’s behavior can be manipulated through configuration, so unless you have some specific reason to do otherwise, you should prefer it.
EXAM TIP

There are several questions in the exam that show you a section of a configuration file on
one side of the screen, with blank boxes over key elements, and the available choices on
the other side of the screen. You are asked to drag and drop those elements in the correct
places. You need to get all the items correct in order to get the question right.

Configuring service behaviors
For any given application, you can have it configured as a service, as a client, or both. The
Tools menu in Visual Studio provides a tool called the WCF Service Configuration Editor,
which enables you to visually manipulate all the XML elements inside the configuration file.
Assuming that you’re trying to configure a service, start the WCF Service Configuration Editor
tool and open your service’s configuration file.

Creating a new service
Assuming that you have not yet configured a service, you can open up the WCF Service
Configuration Editor (as shown in Figure 3-8) and choose the Create a New Service option. If
you created the project as a WCF application, the service already exists, and adding it again
obviously results in a clash. If you already have a service defined, select your existing service
instead of adding everything as outlined in the following steps.

200

CHAPTER 3

Designing and implementing WCF Services

FIGURE 3-8  Create a New Service option

Specifying a new service element (service)
A wizard starts that walks you through the core elements of configuring a WCF Service. The
first thing it does is add the element to the configuration file. It then
adds a element. The wizard then presents the New Service Element Wizard page
that asks you to browse to the assembly containing the service or services you want to configure (see Figure 3-9).



Objective 3.2: Configure WCF services by using configuration settings

CHAPTER 3

201

FIGURE 3-9  New Service Element Wizard page (service)

Specifying a new service element (contract)
After you specify the service(s), you need to specify the corresponding contract(s). Unless you
keep the interfaces in a separate assembly, the same assembly will contain both items (see
Figure 3-10).

FIGURE 3-10  New Service Element Wizard page (contract)

202

CHAPTER 3

Designing and implementing WCF Services

Specifying a new service element (communication mode)
Next, a wizard page asks you to define the communication mode you want to use (see Figure
3-11). Keep in mind that the wizard presents only 5 options; however, there are at least 12
out-of-the-box options available, and you can certainly create your own by making the number of available ones infinite.

FIGURE 3-11  New Service Element Wizard page (communication mode)

Specifying a new service element (interoperability mode)
The next step asks you to choose between Basic Web Services Interoperability and Advanced
Web Services Interoperability. If you choose the Advanced option, you can also specify Duplex or Simplex communication, as shown in Figure 3-12.



Objective 3.2: Configure WCF services by using configuration settings

CHAPTER 3

203

FIGURE 3-12  New Service Element Wizard page (interoperability mode)

Resulting configuration file
Screen shots aren’t helpful for the next two pages of the wizard because you are simply asked
for the endpoint address and then you see a summary page that shows you all your options.
Using the wizard isn’t the goal, but showing you how to use configuration for services is. The
resulting output is instructional:





binding="wsDualHttpBinding" bindingConfiguration="" name="DualHttp"
contract="Samples.WCF.Services.ITestService" />





At the outermost level, underneath the node, you’ll see the ServiceModel> definition. Underneath that node is the node; the pluralization
should be enough to indicate that one or more items can be added to it (in this case, service
definitions). Underneath that is the node and the main item related to it, the Name
attribute. The name is the fully qualified type name of the service, and a matching type
needs to be available somewhere along the probing path the runtime uses for assemblies.

204

CHAPTER 3

Designing and implementing WCF Services

Contained in the element is the element, and the ABCs are included:
The address, the binding (in this case, I added a name for the binding, although it’s not
technically necessary), and the contract are all specified. The contract type and the service
type are the primary plumbing employed, so both of those types need to be visible to
assemblies that the host application can load.
At this point, as simple as it might appear, you have accomplished all the following:
■■

Configured a service

■■

Configured an endpoint

■■

Configured a binding

■■

Specified a service

■■

Specified a service contract

The only things left to cover are exposing service metadata and configuring service
behaviors.

Exposing service metadata
Metadata endpoints all begin with the prefix “mex,” which is an abbreviation for “metadata
exchange.” Currently, there are four out-of-the-box endpoints:
■■

mexHttpBinding

■■

mexHttpsBinding

■■

mexNamedPipeBinding

■■

mexMsmqBinding

Each corresponds to the underlying binding, and yes, you could certainly opt to expose all
of them if the situation necessitated it. Let’s use the previous snippet, but change the duplex
binding to a more common one (wsHttpBinding) and then add a mexHttpBinding. To do so,
add another element under the element of type mexHttpBinding. Unlike bindings
for non-mex endpoints, metadata exchange endpoints don’t require an address:

binding="wsHttpBinding" bindingConfiguration="" name="WsHttp"
contract="Samples.WCF.Services.ITestService" />
name="Mex" contract="IMetadataExchange" />


The portion in bold shows the addition of the mex binding. This makes metadata exchange
possible, and if you hit the endpoint (which is added by default starting with version 4.0)
you’ll see the wsdl of the service, which clients can use to gather whatever information you
made available about the service.
The last thing you need to know is the BehaviorConfiguration of the service. Many
things in WCF can be fine-tuned by using behaviors, the two broad categories being



Objective 3.2: Configure WCF services by using configuration settings

CHAPTER 3

205

EndpointBehaviors and ServiceBehaviors. EndpointBehaviors enable you to specify
(unsurprisingly) information about endpoints. This information includes clientCredentials,
transaction batching, the DataContract serializer, and much more.
There are also ServiceBehaviors that enable you to control several aspects of the service at
a granular level. Several examples of these are shown in Figure 3-13.
Like any advanced features, ServiceBehaviors and EndpointBehaviors can be a doubleedged sword. There are many problems that require the manipulation of either or both of
these behaviors and enable you to do things that would otherwise be awkward and problematic. At the same time, they can be the source of many problems if they aren’t understood.
The default configuration settings that WCF provides enable you to do quite a bit out of the
box, but if your service supports any degree of high volume or requires sophisticated security,
you’ll almost certainly have to manipulate some of these items.
If you’re using the WCF Service Configuration Editor tool, you can simply navigate to the
Advanced node, click the Service Behaviors node, and then choose New Service Behavior
Configuration. Make sure that you give it a name so you can easily reference it afterward.
Figure 3-13 shows a list of the available out-of-the-box behavior extensions you can add to a
service.

FIGURE 3-13  Service behavior element extensions

Simply pick the item(s) that you want added, and then click Add. Afterward, you can click
the Service node, and any new behaviors you added will be available in the drop-down

206

CHAPTER 3

Designing and implementing WCF Services

list. If you don’t name the behaviors, the default is to have them named NewBehavior0,
NewBehavior1, NewBehavior2, and so on.
When you add a service behavior, it’s added to the element and the specifics are included in the element (which would differentiate it from an
endpoint behavior, for example). Again building on the example, the end result would look
like the following:










binding="wsHttpBinding" bindingConfiguration="" name="WsHttp"
contract="Samples.WCF.Services.ITestService" />
contract="IMetadataExchange" />




The link between the ServiceBehavior and the Service is the Behavior's Name attribute and
the Service's BehaviorConfiguration attribute. These need to match in order to be associated.
One item that doesn’t exactly fit in the objective set coverage, but will likely be on the
exam, is ProtocolMapping, which enables you to specify a relationship between transport
protocol schemes (http, net.pipe, and https) and the corresponding WCF bindings. You can
define ProtocolMappings so that they apply to all hosted applications by modifying the
machine.config file. Conversely, you can limit the scope of the mappings so that they apply
only to an individual application. In either case, you do it the same way; the only difference is
where you change the values (in the machine.config file to apply the mappings globally, or in
app.config/web.config to apply them to a specific application).







Configuring service endpoints
As stated earlier, the element enables you to specify both ServiceBehaviors
and EndpointBehaviors. A typical EndpointBehavior that you need to configure is one
related to security: clientCredentials. (Security is covered later in this chapter; but real

Objective 3.2: Configure WCF services by using configuration settings

CHAPTER 3

207

ize that this is something you might need to do to meet a security requirement.) To facilitate this, a new EndpointBehavior is added through the WCF Service Configuration Editor,
which is shown in Figure 3-14. The EndpointBehavior is added, and using wsHttpEndpoint, the BehaviorConfiguration attribute is specified and named. Again, just as with the
ServiceBehavior, the Name property is the link between the two.

FIGURE 3-14  Adding an endpoint behavior

The resulting output follows:















behaviorConfiguration="wsHttpBehaviorSample" binding="wsHttpBinding"

208

CHAPTER 3

Designing and implementing WCF Services

bindingConfiguration="" name="WsHttp"
contract="Samples.WCF.Services.ITestService" />
contract="Samples.WCF.Services.ITestService" />




Configuring bindings
Next, a new BindingConfiguration is added for the wsHttpBinding. Figure 3-15 illustrates
all the available options in the Create a New Binding dialog box (and shows that the
wsHttpBinding has been selected):

FIGURE 3-15  Adding a binding configuration

In the current project, there was not a ProtocolMapping defined for the wsHttpBinding, so
one was added. Using the editor, you can select the Protocol Mapping node, select New, and
choose the Binding, the Binding Configuration, and the Scheme. The resulting configuration
items look like the following:

bindingConfiguration="wsHttpBindingConfig​
Sample" />







Although this is perfectly valid, it’s rather contrived. A more realistic example might be
to change the mapping that’s already there. For example, as you can see from the original


Objective 3.2: Configure WCF services by using configuration settings

CHAPTER 3

209

Protocol Mapping window, the http scheme was mapped to the basicHttpBinding. Perhaps
you want the default binding to be the wsHttpBinding instead (and because the configuration
is already built, you might as well go ahead and specify it). You simply click the existing
scheme, select Edit, and then change the binding, adding in the binding configuration if the
requirements dictate the need. The resulting ProtocolMapping looks like this instead:


bindingConfiguration="wsHttpBindingConfigSample" />


So what exactly would happen if you made this last change? If you initially failed to identify an endpoint for the HTTP type base address, one would be created by default (starting
with WCF version 4.0; prior to that you had to specify an endpoint), but it would be of type
basicHttpBinding. Now, if an endpoint isn’t specified, the default for HTTP is wsHttpBinding.
Both basicHttpBinding and wsHttpBinding are similar in that they are both designed to
communicate over HTTP. There is nothing stopping you from changing the defaults to something totally different. So the default binding for http when no endpoint is defined could be a
netNamedPipeBinding (or any other one you can think of). Although there’s nothing stopping you from doing this, just because you can do something doesn’t mean you necessarily
should—or that it makes sense to do so.
The best-case scenario is that you would explicitly define an http endpoint, and no defaults would be needed. But what if you didn’t? Do netNamedPipeBindings have the same
addressing scheme as the http bindings do? Do they have the same ones as the tcpBindings
or the Msmq bindings? No, they don’t. Other than being confusing, the chances of it causing major problems are high, and it’s hard to see how there’d be any benefit. If you need
a default endpoint for any given binding that isn’t already provided, you can add it via
ProtocolMapping, but you would want to do it so the scheme corresponds to the binding.
Otherwise, you’re just as likely to cause some unpredictable behavior in the process.
EXAM TIP

Remember that, even if you don’t know the answer to a question, if you can eliminate any
wrong choices you immediately increase your chances of getting the item correct. On the
new versions of the exam, in which you have all the drag-and-drop items, you have to get
several things right in order to get the item correct, and you might find a question that has
three empty boxes that need answers, but x (where x > 3) available choices. In the previous
item, just by reviewing the resulting items that are created from the configuration file, you
can know that the answer will have either binding=somebinding or bindingconfiguration
=someconfiguration (or both) because they are the only two possible attributes that are
available outside of scheme. If the only bindings you saw were netMsmqBinding or new​
NamedPipeBinding, that is your answer, even if the use case isn’t something that you
would typically want to do because no other attributes are allowed to exist there.

210

CHAPTER 3

Designing and implementing WCF Services