我正在尝试抽象/封装以下代码,因此所有客户端调用都不需要重复此代码。例如,这是从视图模型 (MVVM) 到 WCF 服务的调用:
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
. 请注意,在调用时WcfChannelFactory
嵌入自身。这就是视图模型在处理后尝试使用它的原因/方式。WcfClientProxy
CreateChannel()
如何抽象此代码,以使我的视图模型调用尽可能简单,同时正确处理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());