我正在尝试抽象/封装以下代码,以便所有客户端调用都不需要重复此代码。例如,这是一个电话,从一个视图模型(MVVM)到WCF服务:Tricky IDisposable问题
using (var channelFactory = new WcfChannelFactory<IPrestoService>(new NetTcpBinding()))
{
var endpointAddress = ConfigurationManager.AppSettings["prestoServiceAddress"];
IPrestoService prestoService = channelFactory.CreateChannel(new EndpointAddress(endpointAddress));
this.Applications = new ObservableCollection<Application>(prestoService.GetAllApplications().ToList());
}
我在重构原始尝试是要做到这一点:
public static class PrestoWcf
{
public static IPrestoService PrestoService
{
get
{
using (var channelFactory = new WcfChannelFactory<IPrestoService>(new NetTcpBinding()))
{
var endpointAddress = ConfigurationManager.AppSettings["prestoServiceAddress"];
return channelFactory.CreateChannel(new EndpointAddress(endpointAddress));
}
}
}
}
这使得我的观点模型拨打电话只有一个,现在的代码行:
this.Applications = new ObservableCollection<Application>(PrestoWcf.PrestoService.GetAllApplications().ToList());
但是,我得到了WcfChannelFactory
已经配置错误。这是有道理的,因为当视图模型尝试使用它时,它确实被放弃了。但是,如果我删除了using
,那么我没有正确处理WcfChannelFactory
。请注意,当CreateChannel()
被调用时,WcfChannelFactory
嵌入WcfClientProxy
中。这就是为什么视图模型在处理完成后试图使用它的原因。
如何抽象此代码,以保持我的视图模型调用尽可能简单,同时正确处理WcfChannelFactory
?我希望我解释得很好。
编辑 - 已解决!
基于牛排答案,这做到了:
public static class PrestoWcf
{
public static T Invoke<T>(Func<IPrestoService, T> func)
{
using (var channelFactory = new WcfChannelFactory<IPrestoService>(new NetTcpBinding()))
{
var endpointAddress = ConfigurationManager.AppSettings["prestoServiceAddress"];
IPrestoService prestoService = channelFactory.CreateChannel(new EndpointAddress(endpointAddress));
return func(prestoService);
}
}
}
这里是视图模型电话:
this.Applications = new ObservableCollection<Application>(PrestoWcf.Invoke(service => service.GetAllApplications()).ToList());
+1使用Func返回您的应用程序,而不是带有副作用的操作! – 2013-05-06 02:54:03