Learning WCF Chapter1 Exposing Multiple Service Endpoints

时间:2022-07-02 02:40:14

Learning WCF Chapter1   Exposing Multiple Service Endpoints

So far in this chapter,I have shown you different ways to create services,
how to expose a service endpoint and metadata exchange endpoint,
how to generate client proxies,
how to work with metadata,
and how to configure service behaviors.
In this section,I’ll place the emphasis on endpoints,binding configuration,and allocation of assemblies for a more complex solution.

WCF includes a number of standard bindings that allow you to quickly configure a service for a particular set of protocols.
Clients must use compatible protocols when they communicate with each endpoint.
Services can expose multiple endpoints for the same service contract in order to expose functionality over different protocols.
For example,a service may be called by internal clients over TCP,but by external clients over HTTP.
In addition to supporting different protocols,internal and external clients may not have access to the same service contracts.
Some operations may be allowed only by clients within the domain,while others are publicly available to remote clients on the Internet.

In this lab you will configure multiple endpoints for a service to support different endpoint and binding configurations.
In the process you’ll explore the following concepts:
• Hosting multiple services
• Configuring multiple endpoints for a service
• Accessing a service from a Windows client application
• Initializing proxies from multiple endpoint and binding configurations
• Comparing proxy generation to sharing types between services and clients

Lab: Hosting Multiple Services and Sharing Types

In this lab,you’ll modify an existing solution to implement a service contract and an administrative contract on two distinct services.
You’ll then host each service in the same host process,a console application.
An internal client presumed to be behind the firewall will consume each service using network protocols such as TCP and named pipes.
This client will have access to service operations exposed by the service contract and administrative contract.
An external client,presumed to be accessing the service over the Internet will have access only to operations exposed by the service contract over HTTP.
The internal client will share class libraries to access service contracts,while the external client will use traditional methods for generating service proxies.

Implementing multiple contracts on a service
In this section,you’re going to implement the predefined service contracts on two distinct services.
Each service will expose two contracts: one for business functionality core to the service,the other for administrative functionality.
Both services will implement the same administrative contract.
This illustrates an example of contract factoring for reuse.
1. Start by opening the solution <YourLearningWCFPath>\Labs\Chapter1\MultiContractService\MultiContractService.sln.
This solution contains several shell projects,including a service library,a host,and two Windows client applications as follows:

BusinessServiceContracts
A class library containing three contracts: IAdmin, IServiceA,and IServiceB.
IAdmin defines administrative operations.
IServiceA and IServiceB respectively describe functionality to be exposed by ServiceA and ServiceB.

BusinessServices
A class library that will contain two services: ServiceA and ServiceB.

Host
A console application that will host ServiceA and ServiceB.

InternalClient
A windows client application that will access services behind the firewall.

ExternalClient
A windows client application that will access services over the Internet.

Note:Putting service contracts into a separate class library facilitates sharing metadata with client applications when you own both sides of the development effort.

2. The first thing you’ll do is provide an implementation for ServiceA,which is located in the BusinessServices class library.
First,take a look at the contracts you will implement.
Go to the BusinessServiceContracts project and open IServiceA.cs; you’ll see a contract with two operations.
Now open IAdmin.cs and you’ll see another contract with two different operations.
To implement these contracts,go to the BusinessServices project.
First,add a reference to the BusinessServiceContracts project so you can access the contracts it defines.
Then open ServiceA.cs and add a using statement for the BusinessServiceContracts namespace, as shown here:

using BusinessServiceContracts;

Modify the definition of ServiceA so that it derives from IServiceA and IAdmin as follows:

public class ServiceA : IServiceA, IAdmin

Implement both contracts implicitly.
You can use a shortcut by hovering your mouse over IServiceA and using the smart tag to select “Implement interface IServiceA,” as shown in Figure 1-29.

关于自动实现接口的方法,可以参看这篇文章的说明Automatic Code Generation-->Implement Interface

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Figure 1-29. Using smart tags to implement an interface

Example 1-17. Implementation for ServiceA

 public class ServiceA : IServiceA, IAdmin
{
public string Operation1()
{
return "IServiceA.Operation1() invoked.";
} public string Operation2()
{
return "IServiceA.Operation2() invoked.";
} public string AdminOperation1()
{
return "IAdmin.AdminOperation1 invoked.";
} public string AdminOperation2()
{
return "IAdmin.AdminOperation2 invoked.";
}
}

3. Follow a similar set of steps to implement ServiceB.
Open ServiceB.cs and derive the class from IServiceB and IAdmin.
Implement both interfaces implicitly so that the result looks like the code in Example 1-18.
Don’t forget to add the using statement for the BusinessServiceContracts namespace.

Example 1-18. Implementation for ServiceB

using BusinessServiceContracts;

namespace BusinessServices
{
public class ServiceB : IServiceB, IAdmin
{
public string Operation3()
{
return "IServiceB.Operation3() invoked.";
} public string AdminOperation1()
{
return "IAdmin.AdminOperation1 invoked.";
} public string AdminOperation2()
{
return "IAdmin.AdminOperation2 invoked.";
}
}
}

4. Verify that the BusinessServices project compiles without error.

Hosting two services with multiple contracts
Now you will host both services in a single console application.
This will require you to create two ServiceHost instances and provide two <service> configuration sections, one for each service type.
1. First,make sure the Host project can access the service contracts and service types.
Go to the Host project and add assembly references to two projects:
BusinessServiceContracts and BusinessServices.

2. In the application configuration file provided for the Host,provide configuration settings for both services.

可以通过右键app.config-->编辑wcf配置,新建服务的时候,通过浏览对应是服务类库,新建终结点绑定契约的时候,浏览对应的契约类库

具体使用方法可以参考这个   wcf 配置文件

Open the app.config file and add the <system.serviceModel> section shown in Example 1-19.
This section belongs inside the <configuration> section of the file.

The configuration section for ServiceA exposes two endpoints for the service contract IServiceA:
one for Internet access over HTTP,another for TCP access behind the firewall.

Learning WCF Chapter1   Exposing Multiple Service Endpoints

ServiceB also exposes two endpoints for the service contract IServiceB:
one for Internet access and another for named pipe access restricting communications to the same machine.

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Both services expose the IAdmin contract over TCP and named pipes,respectively,allowing callers on the same machine,or on remote machines behind the firewall.
Each service configuration also provides the appropriate base addresses for the protocols they support across all endpoints.

Example 1-19. Service model configuration for ServiceA and ServiceB

务必要注意<serviceMetadata httpGetEnabled="true" />  <serviceMetadata httpsGetEnabled="true" />

http和https所有区别的,一定不要弄错了

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="BusinessServices.ServiceA">
<endpoint address="ServiceA" binding="basicHttpBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IServiceA" />
<endpoint address="ServiceA" binding="netTcpBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IServiceA" />
<endpoint address="Admin" binding="netTcpBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IAdmin" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000" />
<add baseAddress="net.tcp://localhost:9000" />
</baseAddresses>
</host>
</service>
<service behaviorConfiguration="ServiceBehavior" name="BusinessServices.ServiceB">
<endpoint address="ServiceB" binding="basicHttpBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IServiceB" />
<endpoint address="ServiceB" binding="netNamedPipeBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IServiceB" />
<endpoint address="Admin" binding="netNamedPipeBinding" bindingConfiguration=""
contract="BusinessServiceContracts.IAdmin" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8001" />
<add baseAddress="net.pipe://localhost" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

Note:

Each <service> section holds configuration settings for its own base addresses and endpoints.
Recall that the configuration for a particular service is used to initialize a ServiceHost instance for that service type.
Be mindful that base addresses across all sections must have unique ports since a port can be opened only once per machine.

3. Now that service model configuration has been provided for each service,you will write code to initialize and open a ServiceHost instance for both.
Go to the Host project and open Program.cs.
Modify the Main( ) entry point so that it includes the code shown in Example 1-20.
You will also need to add a using statement for System.ServiceModel.

This code creates two distinct ServiceHost instances,one for each service.
They are both constructed and opened within a try…finally block to ensure that Close( ) is called for each when the host shuts down or if a fatal exception occurs.
In addition,the code calls Abort() if the ServiceHost instance is in a faulted state, since Close() would throw an exception in this case.

Example 1-20. Initializing the ServiceHost for ServiceA and ServiceB

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel; namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost hostA = null;
ServiceHost hostB = null;
try
{
hostA = new ServiceHost(typeof(BusinessServices.ServiceA));
hostB = new ServiceHost(typeof(BusinessServices.ServiceB));
hostA.Open();
hostB.Open(); Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate Host");
Console.ReadLine();
}
finally
{
CloseHost(hostA);
CloseHost(hostB);
}
} static void CloseHost(ServiceHost host)
{
if (host == null)
{
throw new ArgumentNullException();
}
if (host.State == CommunicationState.Faulted)
{
host.Abort();
}
else
{
host.Close();
}
}
}
}

4. Compile and run the Host project once to verify that no errors occur.
Because metadata browsing is enabled in the configuration section for each service type,
you can browse to the WSDL document for each service by providing the HTTP base address for each service.
Note that each service has its own distinct WSDL document,
but for each individual service,all endpoints for the service are included in its WSDL document.

Learning WCF Chapter1   Exposing Multiple Service Endpoints

遍历ServiceHost.Description.Endpoints打印出,服务中的所有终结点。尝试用浏览器访问,居然不行。不知道是什么问题。

找到原因了:尼玛,try finally最终的finally,不管是否有异常都会执行。服务刚打开就TM被关闭了

修改代码

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description; namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost hostA = null;
ServiceHost hostB = null;
try
{
hostA = new ServiceHost(typeof(BusinessServices.ServiceA));
hostB = new ServiceHost(typeof(BusinessServices.ServiceB));
hostA.Open();
hostB.Open();
ServiceEndpointCollection listA = hostA.Description.Endpoints;
foreach (ServiceEndpoint item in listA)
{
Console.WriteLine(item.Address);
}
Console.WriteLine();
listA = hostB.Description.Endpoints;
foreach (ServiceEndpoint item in listA)
{
Console.WriteLine(item.Address);
}
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate Host");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
CloseHost(hostA);
CloseHost(hostB);
}
Console.ReadLine();
CloseHost(hostA);
CloseHost(hostB);
} static void CloseHost(ServiceHost host)
{
if (host == null)
{
throw new ArgumentNullException();
}
if (host.State == CommunicationState.Faulted)
{
host.Abort();
}
else
{
host.Close();
}
}
}
}

注意,只有下面2个链接是可以在浏览器中访问的

http://localhost:8000/?wsdl

Policy相当于Contract   binding和service都是和wcf中相对应的

Learning WCF Chapter1   Exposing Multiple Service Endpoints

http://localhost:8001/?wsdl

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Consuming internal services using shared contracts
In this part of the lab,you will implement the internal client application and invoke service operations over TCP and named pipe protocols.
The purpose of this exercise is to illustrate how you might share service metadata when you own both sides of the development effort for intranet clients. Sharing contract libraries ensures both sides are compiling against the latest contract versions throughout the development cycle.
In addition,this exercise will illustrate the use of different standard bindings for TCP and named pipes.

1. First,go to the InternalClient project and add a reference to the BusinessServiceContracts project.
This will give the client application direct access to the service contract necessary to invoke the service.

2. The client application requires prior knowledge of the service endpoints it can reach before it can configure a proxy.
Under the assumption that you own both sides,client developers will manually configure client endpoints to reach each service endpoint.
In this case,you’ll consume ServiceA over TCP and ServiceB over named pipes.

Open the app.config file and add the <system.serviceModel> section shown in Example 1-21.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="net.tcp://localhost:9000/ServiceA" binding="netTcpBinding"
bindingConfiguration="" contract="BusinessServiceContracts.IServiceA" />
<endpoint address="net.tcp://localhost:9000/Admin" binding="netTcpBinding"
bindingConfiguration="" contract="BusinessServiceContracts.IAdmin"
name="TCP_IAdmin" />
<endpoint address="net.pipe://localhost/ServiceB" binding="netNamedPipeBinding"
bindingConfiguration="" contract="BusinessServiceContracts.IServiceB" />
<endpoint address="net.pipe://localhost/Admin" binding="basicHttpBinding"
contract="BusinessServiceContracts.IAdmin" name="IPC_IAdmin" />
</client>
</system.serviceModel>
</configuration>

This includes two endpoints for each service:
one for the main service contract,
the other for the administrative contract.
The binding for each endpoint matches the binding configuration for the same endpoint at the service.
In this case,TCP endpoints use netTcpBinding,and named pipe endpoints use netNamedPipeBinding.

Note:
Remember that when you select a binding,you are selecting a transport protocol,a message encoding format,and possibly other messaging protocols for security and reliability,for example.
The details of what goes into a binding will be discussed in Chapter 3.
The important thing is that if you use the defaults on both sides,the communication channel at each end will be compatible.

3. Now you will write some code to invoke each service endpoint on both services.
To do this, you will need four proxy references:
one for each service and contract.
Open Form1.cs and add a using statement for BusinessServiceContracts.
In addition,declare a proxy for each contract,scoped to the lifetime of the application, adding the following definitions as members of Form1:

using BusinessServiceContracts;
IServiceA proxyA;
IAdmin adminProxyA; IServiceB proxyB;
IAdmin adminProxyB;

4. In the form constructor,initialize each proxy using ChannelFactory<T>.
The proxies for IServiceA and IServiceB can use the default client endpoint for each contract.
Because there is only one endpoint for each contract type,you don’t have to specify which <endpoint> section will initialize the proxy.
Since IAdmin has two endpoints defined,one for TCP and another for named pipes,you must specify which endpoint will initialize the proxy when you construct ChannelFactory<T>.
Do this by passing the appropriate endpoint name from Example 1-21.
You’ll see the resulting code for the form constructor in Example 1-22.
You must also add a reference to System.ServiceModel, as shown.

Example 1-22. Code to initialize ServiceA and ServiceB proxies

using System.ServiceModel;
public Form1()
{
InitializeComponent();
CreacteProxy();
} private void CreacteProxy()
{
//IServiceA和IServiceB对应的终结点只有1个,无需通过终结点的名称来区分
ChannelFactory<IServiceA> factoryA = new ChannelFactory<IServiceA>();
ChannelFactory<IServiceB> factoryB = new ChannelFactory<IServiceB>(); //IAdmin有2个终结点,所以需要通过终结点的名字来区分
ChannelFactory<IAdmin> adminFactoryA = new ChannelFactory<IAdmin>("TCP_IAdmin");
ChannelFactory<IAdmin> adminFactoryB = new ChannelFactory<IAdmin>("IPC_IAdmin"); proxyA = factoryA.CreateChannel();
proxyB = factoryB.CreateChannel(); adminProxyA = adminFactoryA.CreateChannel();
adminProxyB = adminFactoryB.CreateChannel();
}

5. The user interface for the client has already been created.
If you look at Form1.cs in design view,you’ll see a button to test each service and administrative operation.
Now you’ll add code to invoke each operation using the appropriate proxy.
For each button on the form,add a handler for the Click event;
you can do this by double-clicking each button from design view.
Inside each Click event handler,add code to invoke the appropriate operation and show the result in a message box.
The resulting code for each of these handlers is shown in Example 1-23.

Note:
Just adding the code from Example 1-23 will not be sufficient to hook up the event handlers.
When you double-click each button in design view,this generates designer code to hook up each event handler to its Button control.

Example 1-23. Code to invoke all service operations

        private void buttonServiceA_AdminOperation1_Click(object sender, EventArgs e)
{
message = adminProxyA.AdminOperation1();
MessageBox.Show(message);
} private void buttonServiceA_AdminOperation2_Click(object sender, EventArgs e)
{
message = adminProxyA.AdminOperation2();
MessageBox.Show(message);
} private void buttonServiceB_AdminOperation1_Click(object sender, EventArgs e)
{
message = adminProxyB.AdminOperation1();
MessageBox.Show(message);
} private void buttonServiceB_AdminOperation2_Click(object sender, EventArgs e)
{
message = adminProxyB.AdminOperation2();
MessageBox.Show(message);
} private void buttonServiceA_Operation1_Click(object sender, EventArgs e)
{
message = proxyA.Operation1();
MessageBox.Show(message);
} private void buttonServiceA_Operation2_Click(object sender, EventArgs e)
{
message = proxyA.Operation2();
MessageBox.Show(message);
} private void buttonServiceA_Operation3_Click(object sender, EventArgs e)
{
message = proxyB.Operation3();
MessageBox.Show(message);
}

6. It is always good practice to release resources when you are finished with them.
To make sure that each of the channels are properly disposed of when the application exits,add code to explicitly close each proxy.
First,add a new private function named CloseProxy( ) that will cast each proxy to ICommunicationObject
and invoke its Abort() operation if the proxy is in the faulted state,
and call the Close( ) operation otherwise.
Then,add an event handler for the FormClosing event of Form1 and add code to call CloseProxy( ) for each proxy.
The code to add is shown in Example 1-24.

Example 1-24. Code to close each proxy

private void CloseProxy(ICommunicationObject proxy)
{
if (proxy != null)
{
if (proxy.State == CommunicationState.Faulted)
{
proxy.Abort();
}
else
{
proxy.Close();
}
}
} private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
CloseProxy(proxyA as ICommunicationObject);
CloseProxy(adminProxyA as ICommunicationObject);
CloseProxy(proxyB as ICommunicationObject);
CloseProxy(adminProxyB as ICommunicationObject);
}

7. Compile the solution and test the internal client.
Run the Host project first,and then run InternalClient.
Click each button to invoke operations exposed by ServiceA and ServiceB.

Consuming external services with a generated proxy

在外部访问的话,需要通过http来添加服务引用的方式生成代理
Now you will implement the external client application and invoke service operations over HTTP.
In this case,the client will rely on the WSDL document to generate a proxy and related configuration to call the service.
This exercise will illustrate how the proxy generation process handles multiple contracts and endpoints.

1. Start by running the Host project without debugging so that you can generate proxies for each service.

2. Go to the ExternalClient project in Solution Explorer and add a service reference for ServiceA.
Provide the base address http://localhost:8000 and provide the namespace ServiceA.
This will generate a proxy for each contract exposed by ServiceA and create an application configuration file with client endpoints.

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Learning WCF Chapter1   Exposing Multiple Service Endpoints

三个终结点,每个终结点都有自己的绑定

Learning WCF Chapter1   Exposing Multiple Service Endpoints

3. Now add a service reference for ServiceB. This time,provide the base address http://localhost:8001 and provide the namespace ServiceB.
This will generate a proxy for each contract exposed by ServiceB,adding new client endpoints to the application configuration file.

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Learning WCF Chapter1   Exposing Multiple Service Endpoints

Note:The application configuration file is not overwritten when you add new service references.    //添加一个新的服务引用的时候,配置文件不会被重写
A merge is performed to add to configuration settings.    //会有一个merge的操作,把新的服务的配置和之前的合并,类似于追加
SvcUtil also supports merge through command-line options.

4. This application will invoke each service using the proxies generated by SvcUtil.
Like with the InternalClient application,you’ll create a proxy reference for each service contract,
initialize them in the form constructor,and then close them in the FormClosing event.
The code will be simplified somewhat since the generated proxy hides some of the complexity of creating the communication channel,
and directly exposes close functionality.
The resulting code is shown in Example 1-25.

Example 1-25. Code to initialize and close generated proxies for ServiceA and ServiceB

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ExternalClient.ServiceA;
using ExternalClient.ServiceB;
using System.ServiceModel; namespace ExternalClient
{
public partial class Form1 : Form
{
ServiceAClient proxyA;
ServiceBClient proxyB; public Form1()
{
InitializeComponent();
InitProxy();
} private void InitProxy()
{
proxyA = new ServiceAClient("BasicHttpBinding_IServiceA");
proxyB = new ServiceBClient("BasicHttpBinding_IServiceB");
} private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//ServiceAClient和ServiceBClient继承自ClientBase<TChannel>类
CloseProxy(proxyA as ICommunicationObject);
CloseProxy(proxyB as ICommunicationObject);
} private void CloseProxy(ICommunicationObject proxy)
{
if (proxy == null)
{
throw new ArgumentNullException();
}
if (proxy.State == CommunicationState.Faulted)
{
proxy.Abort();
}
else
{
proxy.Close();
}
}
}
}

You’ll notice that each proxy is initialized by passing the name of a particular endpoint from the application configuration file.
Each service exposes multiple endpoints,but because this is an Internet client,
the assumption is that the client won’t have permissions to call the TCP
nor be able to invoke services over named pipes (named pipes require same-machine calls).
Still,add service reference generated configuration for all endpoints because the WSDL document includes all endpoints for a service.

每一个服务公开了多个endpoint,但是因为这是一个Internet的客户端,假定客户端既没有权限调用TCP也没有权限调用命名管道(命名管道只有在同一台机器上可用)

添加服务引用的时候,仍然为所有的终结点生成了配置,这是因为wsdl文档中包含了一个服务的所有终结点

5. Now you can add code to invoke each operation.
If you look at the form in design view,you’ll see that only three buttons are present to invoke the collective operations of both service contracts.
Create Click event handlers for each button and add code to invoke each operation through the appropriate proxy.
Example 1-26 shows the resulting code.

Example 1-26. Code to invoke each service operation

 string message = string.Empty;
private void buttonOperation1_Click(object sender, EventArgs e)
{
message = proxyA.Operation1();
MessageBox.Show(message);
} private void buttonOperation2_Click(object sender, EventArgs e)
{
message = proxyA.Operation2();
MessageBox.Show(message);
} private void buttonOperation3_Click(object sender, EventArgs e)
{
message = proxyB.Operation3();
MessageBox.Show(message);
}

6. Compile and test the external client application. First run the Host,and then run ExternalClient.
Click each button to invoke the service operations exposed by ServiceA and ServiceB.

Let’s look at the new concepts and tools introduced in this lab.

Implementing Multiple Contracts
Designing service contracts is not as simple as just exposing existing business components as services.
In all likelihood,services will aggregate calls to many logically related business components.
This requires forethought into the use cases through each service.
Irrespective of this aggregation and design effort,it is still possible that the functionality exposed by a single service should not be lumped into one big service contract.

Here are some cases in which multiple contracts could exist on a single service:
• To separate logically related operations for different features     //针对不同的功能,从逻辑上分离出相关的操作
• To separate queued operations from non-queued operations      //将无排列(无序)的操作,分理出排列的操作
• To provide a different entry point for external and internal consumers of the service     //为调用服务的外部和内部的客户端提供不同的入口点

If your service contracts are implemented on CLR interfaces (as I’ve recommended)
then implementing multiple contracts on a service is as simple as implementing multiple interfaces.
In this lab,each service implements a main service contract(IServiceA and IServiceB, respectively) and an administrative contract (IAdmin).

Contracts can facilitate the logical separation of functionality exposed by a service.
For example,in the lab the main service contract for each service holds core business operations for the service.
The administrative contract provides a consistent set of administrative functions that any service can expose.
Both services implement the same administrative contract,which means both services expose a consistent set of operations,
although the internal implementation may be quite different.
Because of the presumed sensitivity of administrative operations,the lab exposes these operations over TCP or named pipes,
which implies access behind the firewall.
To enable internal applications and business partners to access the core service functionality,
the main service contracts are exposed over two endpoints:
one for TCP or namedpipes, the other for Internet access over HTTP.

Hosting Multiple Services
A ServiceHost instance is required for each service type in order to expose endpoints to calling clients.

When you host in IIS or WAS,a .svc endpoint is supplied for each service type,    //在IIS或者WAS中托管服务时,需要为每一个服务类型创建一个.svc终结点
with a @ServiceHost directive that links the .svc endpoint to the actual service type.    //@ServiceHost会指明.svc终结点对应于哪一个服务类型
Thus,if you have multiple services to host in IIS,
you provide a .svc for each to support message-based activation and configure the service model section as you would for any service type.

In self-hosting environments,you are responsible for initializing each ServiceHost instance.     //在自托管的环境中,你需要负责实例化每一个ServiceHost对象
You can initialize a ServiceHost for each service type as shown here (the complete code listing is shown in Example 1-20):

ServiceHost hostA = new ServiceHost(typeof(BusinessServices.ServiceA));
ServiceHost hostB = new ServiceHost(typeof(BusinessServices.ServiceB));
hostA.Open( );
hostB.Open( );

Each ServiceHost is initialized with its own base addresses and service endpoints according to the <service> section with the matching type (see Example 1-19).
Each ServiceHost can also be programmatically initialized using the techniques illustrated earlier in this chapter.

Proxy Generation for Multiple Contracts and Endpoints
Adding a service reference generates the proxy and configuration settings necessary to access a particular service.
If the service implements multiple contracts,a proxy type is generated for each contract.
For example,in this lab when you add a service reference to ServiceA in the ExternalClient project,
the following proxies are generated—one for IServiceA, another for IAdmin:

public partial class ServiceAClient :System.ServiceModel.ClientBase<ExternalClient.ServiceA.IServiceA>,ExternalClient.ServiceA.IServiceA
public partial class AdminClient :System.ServiceModel.ClientBase<ExternalClient.ServiceA.IAdmin>,ExternalClient.ServiceA.IAdmin

Likewise,when you add a service reference to ServiceB a proxy is generated for both contracts: IServiceB and IAdmin.

Note:
In theory,because the IAdmin service contract is the same for both services,they could share a proxy,
but SvcUtil generates proxy types for all contracts and has no knowledge of the code you have already generated.

In addition to generating proxies,SvcUtil generates the configuration necessary for each endpoint exposed by each service.
SvcUtil always provides a name for each <endpoint> element,so you can specify the correct endpoint to use by name when constructing each proxy.
Example 1-27 shows the client endpoints generated for ServiceA and ServiceB;
the endpoints used in the lab for the ExternalClient are shown in bold.

<endpoint address="http://localhost:8000/ServiceA" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IServiceA" contract="ServiceA.IServiceA"
name="BasicHttpBinding_IServiceA" />
<endpoint address="net.tcp://localhost:9000/ServiceA" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IServiceA" contract="ServiceA.IServiceA"
name="NetTcpBinding_IServiceA">
<identity>
<userPrincipalName value="LUJUNTAO\Administrator" />
</identity>
</endpoint>
<endpoint address="net.tcp://localhost:9000/Admin" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IAdmin" contract="ServiceA.IAdmin"
name="NetTcpBinding_IAdmin">
<identity>
<userPrincipalName value="LUJUNTAO\Administrator" />
</identity>
</endpoint>
<endpoint address="http://localhost:8001/ServiceB" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IServiceB" contract="ServiceB.IServiceB"
name="BasicHttpBinding_IServiceB" />
<endpoint address="net.pipe://localhost/ServiceB" binding="netNamedPipeBinding"
bindingConfiguration="NetNamedPipeBinding_IServiceB" contract="ServiceB.IServiceB"
name="NetNamedPipeBinding_IServiceB">
<identity>
<userPrincipalName value="LUJUNTAO\Administrator" />
</identity>
</endpoint>
<endpoint address="net.pipe://localhost/Admin" binding="netNamedPipeBinding"
bindingConfiguration="NetNamedPipeBinding_IAdmin" contract="ServiceB.IAdmin"
name="NetNamedPipeBinding_IAdmin">
<identity>
<userPrincipalName value="LUJUNTAO\Administrator" />
</identity>
</endpoint>

Although the client may not have network rights to invoke the TCP or named pipe endpoints,
these endpoints are still part of the service description (WSDL) and therefore are visible to the client.

Recall that a WSDL document is created for each service type.
Thus,to prevent remote clients from seeing internal endpoints that they should not access,
you can create different service types for internal and external use—funneling them to the same implementation code.
On external service types,you can expose endpoints only for supported contracts over HTTP.
For internal service types,you can expose internal contracts and TCP and named pipes endpoints.
To modify the lab in support of this scenario, you might see the following service types:

public class ServiceA : IServiceA {...}
public class InternalServiceA : IServiceA, IAdmin {...}
public class ServiceB : IServiceB {...}
public class InternalServiceB : IServiceB, IAdmin {...}

In the host configuration,each service type would be defined in a separate <service> element,exposing only the required endpoints.
A compressed view of the required <service> elements is shown here:

<service name="BusinessServices.ServiceA" ...>
<service name="BusinessServices.InternalServiceA" ...>
<service name="BusinessServices.ServiceB" ...>
<service name="BusinessServices.InternalServiceB" ...>

Note:

The following sample illustrates this scenario: <YourLearningWCFPath>\Samples\ServiceContracts\MultiContractServices_UniqueServiceTypes.

Proxy Initialization and Lifetime
Each client proxy opens a communication channel to invoke a service endpoint.
The proxy can be programmatically initialized in code or declaratively initialized per the client’s service model configuration.
If there is only one endpoint configured for a particular service contract,
there is no need to specify an endpoint configuration name to the constructor of the channel factory or proxy.

When you use ChannelFactory<T> to create the channel from the default endpoint,you pass empty quotes to the constructor.
This example expects that only one endpoint is configured for IServiceA:

ChannelFactory<IServiceA> factoryA = new ChannelFactory<IServiceA>("");
m_proxyA = factoryA.CreateChannel( );

Generated proxies provide a default constructor to achieve the same result:

m_proxyA = new ExternalClient.ServiceA.ServiceAClient( );

On the other hand,when multiple endpoints exist for the same contract,
you must provide a configuration name as shown here for ChannelFactory<T> and for a generated proxy:

ChannelFactory<BusinessServiceContracts.IServiceA> factoryA = new ChannelFactory<BusinessServiceContracts.IServiceA>("BasicHttpBinding_IServiceA");
proxyA = factoryA.CreateChannel( );
m_proxyA = new ExternalClient.ServiceA.ServiceAClient("BasicHttpBinding_IServiceA");

In either case,the lifetime of the communication channel is controlled by the proxy reference.
If the client application intends to invoke the service endpoint repeatedly,it is better not to recreate the proxy each time an operation is invoked. Instead,the proxy should be scoped to the lifetime of the application.

When the application is shutting down,you should close the proxy to speed up the release of resources.
When you are working with a channel factory to create the proxy reference,you must cast to ICommunicationObject in order to call its Close( ) method (see Example 1-24).
The equivalent inline steps would be as follows:

ICommunicationObject proxyACommunication = m_proxyA as ICommunicationObject;
...
proxyACommunication.Close( );

This step is required because the channel factory returns a reference to the service contract,which doesn’t expose a Close( ) method.
Still,the underlying object is a CommunicationObject that implements ICommunicationObject.

Proxies generated with SvcUtil include code to wrap the inner communication channel.
In addition,each generated proxy type implements ICommunicationObject directly, and thus provides a Close( ) method.

Note:
Be aware that the channel stack beneath the proxy reference can be put into a faulted or invalid state.
For example,if the service is no longer available,or if the service throws an exception,or if a timeout occurs at either end.
In this case Close() will throw an exception and Abort()should be called to clean up channel resources.
In Chapter 8,I’ll discuss exception handling.

Another point to note is that the lifetime of the communication channel should not be confused with the lifetime of the service instance instantiated by the host to handle a request.

//另外一个需要注意的:  通信信道的生存周期和服务对象的生存周期是不同的(服务对象是由host生成的,用来处理请求)
In fact,a different service instance may be allocated for every call even if the client uses the same channel.      //客户端每一次调用相同的信道的时候,都会有一个不同的服务对象被分配
This behavior is controlled by the service.
Service instancing and throttling behaviors are covered in Chapter 5.

Sharing Service Contracts
This lab illustrates an alternate approach for sharing metadata with the client.
Instead of generating a proxy using SvcUtil,a class library containing only service contracts is shared by the service library and the internal client application.
This approach is useful in an environment where you own both sides: client and service.
This approach can simplify steps in development,help you avoid the internal complexity of types generated by SvcUtil,
and even allow you to exercise more control over service contract versioning on both ends.
Realistically,remote clients such as Internet clients may not be owned,
which is why the more traditional approach of sharing contracts via add service reference is used.

Duplicating Operations
This lab illustrates exposing two different contracts on each service.
These contracts each have unique operations: a set for the business functionality exposed by the service,and a set for administrative functions.
You may also want to expose a subset of business operations for external clients
while exposing the complete set of business functionality to internal clients.

To achieve this,you could create internal and external interfaces for the service contract,for example: IServiceA and IInternalServiceA.
The external interface,IServiceA,would in this case contain a subset of the functionality exposed by IInternalServiceA (see Example 1-28).

Example 1-28. Internal and external service contracts with duplicate operations

[ServiceContract(Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IServiceA
{
[OperationContract]
string Operation1( );
[OperationContract]
string Operation2( );
}
[ServiceContract(Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IInternalServiceA
{
[OperationContract]
string Operation1( );
[OperationContract]
string Operation2( );
[OperationContract]
string Operation3( );
}

If you expose each of these contracts on their own service types (ServiceA and InternalServiceA,respectively),
external clients will never see the functionality exposed to internal clients because they work from a different WSDL document.
However, the implementation can still be the same for each service implementation.

Note:
The following sample illustrates the scenario: <YourLearningWCFPath>\Samples\ServiceContracts\InternalExternalServiceTypes.sln.