[英]WCF Proxy - Creating a generic invoke method to excute every access to the service
I'm using WCF and I made my own proxy in the client, and i want to create a method using lambda expression or Action that will excute everything. 我正在使用WCF,并在客户端中创建了自己的代理,并且我想使用lambda表达式或Action创建一种方法,以执行所有操作。
Here is my proxy: 这是我的代理:
public class BooksProxy
{
public ChannelFactory<IBooksService> Channel { get; set; }
public BooksProxy()
{
Channel = new ChannelFactory<IBooksService>("endpoint");
}
public IBooksService CreateChannel()
{
return Channel.CreateChannel();
}
}
Here is how i use the proxy: 这是我使用代理的方法:
IBooksService proxy = BooksProxy.CreateChannel();
IList<string> lst = proxy.GetStrings();
((ICommunicationObject)proxy).Close();
I want to do something like this in the BooksProxy class: 我想在BooksProxy类中做这样的事情:
public void Execute(Action<...> action)
{
IBooksService proxy = this.CreateChannel();
/* executing here. */
((ICummunicationObject)proxy).Close();
}
And to call it like this maybe: 并这样称呼它:
IList<string> result = null;
BooksProxy.Execute(proxy => { result = proxy.GetStrings(); });
Not quite sure how to do that... 不太确定该怎么做...
Ok, so I figured how to do it. 好的,所以我想出了办法。
Here is the Proxy, The idea is to make it generic: 这是代理,其目的是使其通用:
public class Proxy<T>
{
public ChannelFactory<T> Channel { get; set; }
public Proxy()
{
Channel = new ChannelFactory<T>("endpoint");
}
public T CreateChannel()
{
return Channel.CreateChannel();
}
}
Now here is the trick : 现在这是窍门:
For void methods : 对于无效方法:
public void Execute(Action<T> action)
{
T proxy = CreateChannel();
action(proxy);
((ICommunicationObject)proxy).Close();
}
For return: 退货:
public TResult Execute<TResult>(Func<T, TResult> function)
{
T proxy = CreateChannel();
var result = function(proxy);
((ICommunicationObject)proxy).Close();
return result;
}
Where the TResult is the returning type. 其中TResult是返回类型。
How to use: 如何使用:
Proxy<IService> proxy = new Proxy();
// for a void method
Proxy.Execute(prxy => prxy.Method());
// for non void method.
var result = Proxy.Execute(prxy => prxy.Method());
So, to sum up, here is how the proxy class should look like: 因此,总而言之,这是代理类的外观:
public class Proxy<T>
{
public ChannelFactory<T> Channel { get; set; }
public Proxy()
{
Channel = new ChannelFactory<T>("endpoint");
}
public T CreateChannel()
{
return Channel.CreateChannel();
}
public void Execute(Action<T> action)
{
T proxy = CreateChannel();
action(proxy);
((ICommunicationObject)proxy).Close();
}
public TResult Execute<TResult>(Func<T, TResult> function)
{
T proxy = CreateChannel();
var result = function(proxy);
((ICommunicationObject)proxy).Close();
return result;
}
}
I recommend this solution for a custom wcf proxy without using any service reference, its really simple and easy. 对于不使用任何服务引用的自定义wcf代理,我建议使用此解决方案,这确实非常简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.