讓我們定義契約的接口:
[ServiceContract]
public interface TheInterface
{
[OperationContract]
string DoWork(string Work);
}
的ChannelFactory
自動創建僅實現接口的代理。
var factory = new ChannelFactory<TheInterface>(new BasicHttpBinding());
var address = new EndpointAddress("http://...");
var client = factory.CreateChannel(address);
// there are no other methods on the "client" reference
// than the interface's DoWork method
client.DoWork("foo");
在另一方面,從ClientBase
繼承的類不僅實現了接口,但也暴露了可以用來改變客戶端的行爲多個附加屬性。
public class TheInterfaceProxy : ClientBase<TheInterface>, TheInterface
{
public TheInterfaceProxy(Binding binding, EndpointAddress address) : base(binding, address) { }
public string DoWork(string Work)
{
return this.Channel.DoWork(Work);
}
}
然後
var address = new EndpointAddress("http://...");
using (var client = new TheInterfaceProxy(new BasicHttpBinding(), address))
{
// DoWork is here
// but multiple other members are there too
// for example - applying a custom endpoint behavior:
client.Endpoint.EndpointBehaviors.Add(new InspectorBehavior());
client.DoWork("bar");
}
其中一個例子簡單行爲用於在客戶端側進行檢查傳入/傳出消息
class InspectorBehavior : IEndpointBehavior
{
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new DispatchInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
#endregion
}
class DispatchInspector : IClientMessageInspector
{
#region IClientMessageInspector Members
public void AfterReceiveReply(ref Message reply, object correlationState)
{
MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
reply = buffer.CreateMessage();
Console.WriteLine("Receiving:\n{0}", buffer.CreateMessage().ToString());
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
Console.WriteLine("Sending:\n{0}", buffer.CreateMessage().ToString());
return null;
}
#endregion
}
沒有答案哪個更好但是:
- 如果你不需要任何東西,但默認的行爲 - 你可以用
ChannelFactory
堅持,這是最簡單的兩個
- 爲任何額外費用,使用
ClientBase
,它需要一個額外的類,但
你好Wiktor,非常感謝你的回覆。檢查InspectorBehavior並且DispatchInspector會在客戶端證明TheInterfaceProxy類的行爲或者什麼?如果是,那麼這兩個類與TheInterfaceProxy類之間的連接如何。問候。 – Lowterm
你似乎錯過了這一行代碼'client.Endpoint.EndpointBehaviors.Add(new InspectorBehavior());'它將檢查器添加到'TheInterfaceProxy'的行爲中。這是用渠道工廠創建的代理不可能實現的。 –
你好,謝謝。我現在知道ChannelFactory和ClientBase編程的區別是什麼。但是,其他差異如異步運行,查詢,資源消耗和速度呢?這兩個類是基於Rest還是SOAP? – Lowterm