WCF学习笔记一:创建WCF程序

创建Solution

1、WCFDataContract:一个类库项目,定义契约数据对象,引用System.Runtime.Serialization程序集。

DataContract
using System;
using System.Runtime.Serialization;

namespace WCFDataContract
{
    [DataContract]
    
public class Person
    {
        [DataMember]
        
public string Name { getset; }
        [DataMember]
        
public int Age { getset; }
        [DataMember]
        
public Contact Contact { getset; }
    }
}

 

 

2、WCFServiceContract:一个类库项目,定义契约,引用System.ServiceMode程序集。

 

ServiceContract
using System;
using System.ServiceModel;
using WCFDataContract;

namespace WCFServiceContract
{
    [ServiceContract]
    
public interface IPersonService
    {
        [OperationContract]
        
int GetPersonAge(string name);

        [OperationContract]
        Contact GetPersonContact(Person person);
    }
}

 

 

3、WCFServiceLibrary:一个类库项目,实现契约。
    也可以创建WCF Service Library项目,自动添加App.config,且编译参数多了/client:"WcfTestClient.exe"

 

ServiceLibrary
using System;
using WCFServiceContract;
using WCFDataContract;

namespace WCFServiceLibrary
{
    
public class PersonService : IPersonService
    {
        
public int GetPersonAge(string name)
        {
            
return name.Length;
        }

        
public WCFDataContract.Contact GetPersonContact(WCFDataContract.Person person)
        {
            Contact contact 
= new Contact();
            contact.Address 
= person.Name + "'s Address";
            contact.Mail 
= person.Name + "@mail.com";
            
return contact;
        }
    }
}

 

 

4、定义服务,有两种定义服务端的方式。
4.1、WCFWebAppService:一个Web Application项目,定义基于IIS的服务。需要引用前三个项目和System.ServiceMode程序集。

a、为WCF服务创建PersonService.svc文件

<%@ ServiceHost Language="C#" Debug="true" Service="WCFServiceLibrary.PersonService" %>

 

b、配置WCF服务Web.config文件。在configuration节点下添加:

Web.config
   <system.serviceModel>
        
<behaviors>
            
<serviceBehaviors>
                
<behavior name="WCFWebAppService.PersonServiceBehavior">
                    
<serviceMetadata httpGetEnabled="true" />
                    
<serviceDebug includeExceptionDetailInFaults="false" />
                
</behavior>
            
</serviceBehaviors>
        
</behaviors>
        
<services>
            
<service behaviorConfiguration="WCFWebAppService.PersonServiceBehavior"
                name
="WCFServiceLibrary.PersonService">
                
<endpoint address="" binding="wsHttpBinding" contract="WCFServiceContract.IPersonService">
                    
<identity>
                        
<dns value="localhost" />
                    
</identity>
                
</endpoint>
                
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            
</service>
        
</services>
    
</system.serviceModel>

 

 

4.2、WCFWinAppService:一个Console Application项目,定义自启动的服务。同样需要引用前三个项目和System.ServiceMode程序集。

 

Program
using System;
using System.ServiceModel;
using WCFServiceLibrary;
using WCFServiceContract;
using System.ServiceModel.Description;

namespace WCFWinAppService
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
using (ServiceHost host = new ServiceHost(typeof(PersonService)))
            {
                host.AddServiceEndpoint(
typeof(IPersonService), new WSHttpBinding(), "http://localhost:9999/personservice");
                
if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior behavior 
= new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled 
= true;
                    behavior.HttpGetUrl 
= new Uri("http://localhost:9999/personservice/metadata");
                    host.Description.Behaviors.Add(behavior);
                }
                host.Opened 
+= delegate { Console.WriteLine("PersonService已经启动,按Enter键终止服务!"); };
                host.Open();
                Console.Read();
            }
        }
    }
}

 

 

另,可以通过App.config配置服务。如下:

a、配置App.config,同创建WCF Service Library项目产生的App.config

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. 
-->
  
<system.serviceModel>
    
<services>
      
<service behaviorConfiguration="WCFServiceLibrary.Service1Behavior"
        name
="WCFServiceLibrary.PersonService">
        
<endpoint address="" binding="wsHttpBinding" contract="WCFServiceContract.IPersonService">
          
<identity>
            
<dns value="localhost" />
          
</identity>
        
</endpoint>
        
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        
<host>
          
<baseAddresses>
            
<add baseAddress="http://localhost:8731/WCFServiceLibrary/PersonService/" />
          
</baseAddresses>
        
</host>
      
</service>
    
</services>
    
<behaviors>
      
<serviceBehaviors>
        
<behavior name="WCFServiceLibrary.Service1Behavior">
          
<!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment 
-->
          
<serviceMetadata httpGetEnabled="True"/>
          
<!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information 
-->
          
<serviceDebug includeExceptionDetailInFaults="False" />
        
</behavior>
      
</serviceBehaviors>
    
</behaviors>
  
</system.serviceModel>
</configuration>

 

b、启动ServiceHost

Program
using System;
using System.ServiceModel;
using WCFServiceLibrary;
using WCFServiceContract;
using System.ServiceModel.Description;

namespace WCFWinAppService
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
using (ServiceHost host = new ServiceHost(typeof(PersonService)))
            {
                host.Opened 
+= delegate { Console.WriteLine("PersonService已经启动,按Enter键终止服务!"); };
                host.Open();
                Console.Read();
            }
        }
    }
}

 

 

5、WCFClientDemo:一个Console Application项目模拟服务的客户端,该项目引用System.ServiceMode程序集。

有两种方式调用服务,一种是定义服务代理类,现实项目中几乎不会这样使用。
另一种是使用ChannelFactory创建服务代理类,如下:

 

 

ClientDemo
using System;
using System.ServiceModel;
using WCFServiceContract;
using WCFDataContract;

namespace WCFClientDemo
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
string url = "http://localhost:9999/personservice";
            
//string url = "http://localhost:8731/WCFServiceLibrary/PersonService";
            
//string url = "http://localhost:6094/PersonService.svc";
            using (ChannelFactory<IPersonService> channelFactory = new ChannelFactory<IPersonService>(new WSHttpBinding(), url))
            {
                IPersonService proxy 
= channelFactory.CreateChannel();
                
using (proxy as IDisposable)
                {
                    Person person 
= new Person();
                    person.Name 
= "Fly";
                    person.Age 
= proxy.GetPersonAge(person.Name);
                    person.Contact 
= proxy.GetPersonContact(person);

                    Console.WriteLine(person.Name);
                    Console.WriteLine(person.Age);
                    Console.WriteLine(person.Contact.Address);
                    Console.WriteLine(person.Contact.Mail);
                }
            }
        }
    }
}

 

 

当然,可以通过配置app.config,如下:

 

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<system.serviceModel>
    
<bindings />
    
<client>
      
<endpoint address="http://localhost:9999/personservice" binding="wsHttpBinding" contract="WCFServiceContract.IPersonService" name="PersonService" />
    
</client>
  
</system.serviceModel>
</configuration>

 

那么在创建ChannelFactory<T>的时候,就无须再指定终结点的绑定和地址了,而只须制定对应的终结点配置名称。

using (ChannelFactory<IPersonService> channelFactory = new ChannelFactory<IPersonService>("PersonService"))

 

代码示例:https://files.cnblogs.com/xujiaoxiang/MyWCFDemo.zip

posted @ 2010-05-25 15:16  翱翔  阅读(1659)  评论(0编辑  收藏  举报