When using WCF, it is always called in using, for example:
using (CnblogsWcfClient client = new CnblogsWcfClient()){ client.Say("Hello, cnblogs.com!");}
Later I found that this was a "scam" of Microsoft. I wrote a blog titled "do not call the WCF Service in the using statement ".
This is called as follows:
CnblogsWcfClient client = new CnblogsWcfClient();client.Say("Hello, cnblogs.com!");try{ client.Close();}catch{ client.Abort();}
Every time such code is written, it is always uncomfortable. After nearly 10 months of such discomfort, I can no longer bear it...
So today, I decided to solve this problem...
From What is the best workaround for the WCF client 'using' block issue? Find Practical Functional C #-Part II and find the correct solution, but the provided code is incomplete. After several hours of exploration, we finally find a satisfactory solution.
The code for making the call of the WCF client "Enjoyable" is as follows:
Code called in the application:
// IUserService is the ServiceContract of WCF, which is the proxy class automatically generated by the client. WcfClient. UseService (IUserService userService) => (userService. GetUser (userId )));
WcfClient implementation code:
public class WcfClient{ public static TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> func) { var chanFactory = new ChannelFactory<TChannel>("*"); TChannel channel = chanFactory.CreateChannel(); TReturn result = func(channel); try { ((IClientChannel)channel).Close(); } catch { ((IClientChannel)channel).Abort(); } return result; }}
The main time to solve this problem is to find the asterisk in the code above. The parameter name corresponding to the asterisk is endpointConfigurationName.
At the beginning, it is difficult to pass a value to the endpointConfigurationName parameter. Later, I studied the automatically generated proxy class and did not have any information related to endpointConfigurationName, but inherited from System. ServiceModel. ClientBase <T>. Then, use ILSPy to decompile the ClientBase <T> code and find this asterisk. For details, see:
Summary
There may be more "Enjoyable" calls to the WCF client method, but I think it is at least more comfortable than the previous method. After solving the problem, the best way to celebrate is to write a blog. It is not just about solving the problem, but also about the excitement of solving the problem!
Author dudu