I am trying to abstract / encapsulate the following code so that all client calls do not need to repeat this code. For example, this is a call from the view model (MVVM) to the WCF service:
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()); }
My initial refactoring attempt was as follows:
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 allows my view models to make a call with only one line of code:
this.Applications = new ObservableCollection<Application>(PrestoWcf.PrestoService.GetAllApplications().ToList());
However, I get an error message that WcfChannelFactory already selected. This makes sense because it is actually used when the view model tries to use it. But, if I delete using , then I do not properly manage WcfChannelFactory . Note: WcfChannelFactory is injected into WcfClientProxy when CreateChannel() called. This is why / how the view model tries to use it after it has been deleted.
How do I draw this code so that it is as simple as possible to display my queries on models, when using WcfChannelFactory ? I hope I explained it quite well.
Change - Solved!
Based on the responses to the steaks, this did the following:
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); } } }
And here is the view model call:
this.Applications = new ObservableCollection<Application>(PrestoWcf.Invoke(service => service.GetAllApplications()).ToList());