我试图抽象/封装以下代码,以便所有客户端调用都不需要重复此代码。例如,这是从视图模型 (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
when 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());