ChannelFactory 可以建立多個(Contract)的通道,可以設計很棒的WCF連線元件。
TChannel 介面必須設定ServiceContract Attribute, 而裡面method要加上OperationContract Attribute
using System.ServiceModel;
namespace WCF {
//Contract Description
[ServiceContract]
public IService {
[OperationContract]
string Say(string something);
}
}
//use configuration setting
var serviceFactory = new ChannelFactory<IService>("*")
//create channel
var service = serviceFactory.CreateChannel();
//call
service.Say("Hello");
若是用傳入字串建立ChannelFactory,底層會去configuration system.serviceModel區塊對應的name
給"*"的話,會去找contact=TChannel完整名稱的第一筆。
另外要注意的是建立channelFactory是有成本的。
private static ConcurrentDiction<string, ChannelFactory> cache = new ConCurrentDictionary<string, ChannelFactory>();
public static ChannelFactory<T> Create<T>(string name) {
var key = string.Format("{0}{1}", typeof(T).AssemblyQualifiedName, name);
return cache.GetOrAdd(key, x => new ChannelFactory<T>(name)) as ChannelFactory<T>;
}
參考資料:
https://docs.microsoft.com/zh-tw/dotnet/framework/wcf/feature-details/how-to-use-the-channelfactory