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: } 那么,具体的服务代理类型就可以通过如下的方式定义了:
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: } 那么现在服务代理的消费者(一般是Presenter层对象),就可以直接实例化服务代理对象,并调用相应的方法(这里的方法与服务契约方法一致)即可,所有关于服务调用的细节均被封装在服务代理中。
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: } 四、局限