1: namespace Artech.Lib 2: { 3: public class ServiceProxyBase<TChannel> 4: { 5: public virtual ServiceInvoker<TChannel> Invoker 6: { get; private set; } 7: 8: public ServiceProxyBase(string endpointConfigurationName) 9: { 10: Guard.ArgumentNotNullOrEmpty(endpointConfigurationName, "endpointConfigurationName"); 11: this.Invoker = new ServiceInvoker<TChannel>(endpointConfigurationName); 12: } 13: } 14: } 那么,具體的服務(wù)代理類型就可以通過如下的方式定義了:
1: using Artech.Lib; 2: using Artech.WcfServices.Contracts; 3: namespace Artech.WcfServices.Clients 4: { 5: public class CalculatorProxy : ServiceProxyBase<ICalculator>, ICalculator 6: { 7: public CalculatorProxy():base(Constants.EndpointConfigurationNames.CalculatorService) 8: { } 9: 10: public int Add(int x, int y) 11: { 12: return this.Invoker.Invoke<int>(calculator => calculator.Add(x, y)); 13: } 14: } 15: 16: public class Constants 17: { 18: public class EndpointConfigurationNames 19: { 20: public const string CalculatorService = "calculatorservice"; 21: } 22: } 23: } 那么現(xiàn)在服務(wù)代理的消費(fèi)者(一般是Presenter層對(duì)象),就可以直接實(shí)例化服務(wù)代理對(duì)象,并調(diào)用相應(yīng)的方法(這里的方法與服務(wù)契約方法一致)即可,所有關(guān)于服務(wù)調(diào)用的細(xì)節(jié)均被封裝在服務(wù)代理中。
1: using System; 2: using Artech.Lib; 3: using Artech.WcfServices.Contracts; 4: namespace Artech.WcfServices.Clients 5: { 6: class Program 7: { 8: static void Main(string[] args) 9: { 10: CalculatorProxy calculatorProxy = new CalculatorProxy(); 11: int result = calculatorProxy.Add(1, 2); 12: Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, result); 13: Console.Read(); 14: } 15: } 16: } 四、局限