若用戶端已有服務合約、與資料合約的參考(如用戶端和服務端都是自己寫的),你可以改用ChannelFactory<T> 來建立proxy,透過它呼叫服務。
例如延續前面範例
- 修改用戶端的Main方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// ServiceReference1.IMyService proxy =
//new ServiceReference1.MyServiceClient();
// string result = proxy.Add(3, 4);
// Console.WriteLine(result);
ServiceReference1.IMyService proxy =
ChannelFactory<ServiceReference1.IMyService>.CreateChannel(
new BasicHttpBinding(),
new EndpointAddress("http://localhost:8732/Design_Time_Addresses/WcfServiceLibrary1/Service1/"));
string result;
result = proxy.Add(3, 4);
Console.WriteLine(result);
if ((proxy as ICommunicationObject).State ==
CommunicationState.Opened)
{
(proxy as ICommunicationObject).Close();
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// ServiceReference1.IMyService proxy =
//new ServiceReference1.MyServiceClient();
// string result = proxy.Add(3, 4);
// Console.WriteLine(result);
ServiceReference1.IMyService proxy =
ChannelFactory<ServiceReference1.IMyService>.CreateChannel(
new BasicHttpBinding(),
new EndpointAddress("http://localhost:8732/Design_Time_Addresses/WcfServiceLibrary1/Service1/"));
string result;
result = proxy.Add(3, 4);
Console.WriteLine(result);
if ((proxy as ICommunicationObject).State ==
CommunicationState.Opened)
{
(proxy as ICommunicationObject).Close();
}
}
}
}
- 按CTRL + F5執行,Client可以正確呼叫Service
沒有留言:
張貼留言