Skip to main content
 首页 » 编程设计

c#之通用 WCF 代理实现

2024年02月06日16pander-it

我正在编写一个代理来访问 WCF 服务,我们可以在其中访问 WCF 服务和客户端代码。

对于服务契约接口(interface)中的每个方法,我正在编写一个这样的方法。

问题是界面中有很多方法,实际上这变成了复制和粘贴练习。

是否有更优雅的方式(使用 lambda 表达式?)不那么冗长?我无法快速弄清楚....

public interface IServiceContract 
{ 
   DataContracts.TypeA Method1(int arg1, string arg2); 
   string Method2(string arg1); 
   DateTime Method3(); 
   int Method4(DataContracts.Input1); 
   // etc............ 
} 
 
 
    public class Proxy : IServiceContract.... 
 
    public DataContracts.TypeA Method1(int arg1, string arg2) 
    { 
        IFileService proxy = null; 
        ChannelFactory<IFileService> factory = null; 
        try 
        { 
            factory = new ChannelFactory<IFileService>("*"); 
            proxy = factory.CreateChannel(); 
            return proxy.Method1(arg1, arg2); 
        } 
        finally 
        { 
            CloseConnection(proxy, factory); 
        } 
    } 
 
 
     public List<AnOtherResultPoco> Method2(string arg1) 
     { 
         IFileService proxy = null; 
         ChannelFactory<IFileService> factory = null; 
         try 
         { 
             factory = new ChannelFactory<IFileService>("*"); 
             proxy = factory.CreateChannel(); 
             return proxy.Method2(args1); 
         } 
         finally 
         { 
             CloseConnection(proxy, factory); 
         } 
    } 
 
    //ad inifinitum for methods,3,4,5... 

请您参考如下方法:

如果你想使用 lambda 分解你的代码,我建议写一个如下所示的方法:

... 
public void ServiceCall(Action<IFileService> action) 
{ 
    IFileService proxy = null; 
    ChannelFactory<IFileService> factory = null; 
    try 
    { 
        factory = new ChannelFactory<IFileService>("*"); 
        proxy = factory.CreateChannel(); 
        return action(proxy); 
    } 
    finally 
    { 
        CloseConnection(proxy, factory); 
    } 
} 

所以你这样调用你的服务方法:

... 
List<AnOtherResultPoco> result; 
MyClass.ServiceCall(p => { result = p.Method2("hello"); }); 
...