WCF Technical Profiling 30: A very useful WCF invoke programming technique [last article]

Source: Internet
Author: User

In a WCF service invocation that is based on a session channel, due to the limited number of concurrent channels, we need to close the channel in time, when encountered some anomalies, we need to forcibly suspend (Abort) channel, the relevant principle, you can refer to my Article "service agent can not be closed in time what will be the consequences?" ". In real enterprise development, as we generally do not allow developers to manually control the opening and closing of a database connection, we generally do not allow developers to manually create, open, Abort, and close the channel, which is what the framework should do. In this article, let's take a look at some programming techniques that allow developers to ignore the existence of a "channel" and invoke a service call like a normal object.

First, the normal way of service invocation

If you create a proxy for a service invocation through channelfactory<tchannel>, the following code fragment describes the client's typical form of service invocation: Calling the service in a using block based on the proxy object and passing the try/ Catch further handles exception handling for service invocation operations. When TimeoutException or communicationexception is captured, the Abort method is invoked to abort the channel. When a program executes to the end of a using, the Dispose method further calls the Close method to shut down the channel.

 class program 
{
static void Main (string[] args)
{
using (CHANNELFACTORY<ICALCULATOR&G T ChannelFactory = new Channelfactory<icalculator> ("CalculatorService"))
{
ICalculator CALCU Lator = Channelfactory.createchannel ();
using (calculator as IDisposable)
{
Try
{
Console.WriteLine ("x + y = {2} when x = {0} and y = {1}", 1, 2, calculator.) ADD (1, 2));
}
catch (timeoutexception)
{
(calculator As Icommunicationobject). Abort ();
Throw;
}
catch (communicationexception)
{
(CALCU Lator as Icommunicationobject). Abort ();
Throw;
}
}
}
Console.read ();
}
}

Second, the use of delegate to implement exception handling and service agent shutdown

Although the above programming method is the correct way of service invocation, in the real application, it is intolerable for me to adopt the above method in every place where the service calls are made. Not only does this make your program look bloated, it also brings in a lot of repetitive code, and the ability to create channelfactory<tchannel> frequently affects performance. We can implement duplicate code (channelfactory<tchannel> creation, service invocation creation, abort and shutdown, and exception handling) in a number of public ways. For this I created the following Serviceinvoker type, which implements calls to the target service through two overloaded invoke methods.

1:using System;
2:using System.Collections.Generic;
3:using System.ServiceModel;
4:namespace Artech.Lib
5: {
6:public class Serviceinvoker
7: {
8:private static dictionary<string, channelfactory> channelfactories = new dictionary<string, ChannelFac Tory> ();
9:private static Object synchelper = new Object ();
10:
11:private static channelfactory<tchannel> getchannelfactory<tchannel> (String Endpointconfigurationna Me
12: {
13:channelfactory<tchannel> ChannelFactory = null;
14:if (Channelfactories.containskey (endpointconfigurationname))
15: {
16:channelfactory = Channelfactories[endpointconfigurationname] as channelfactory<tchannel>;
17:}
18:
19:if (Null = = ChannelFactory)
20: {
21:channelfactory = new channelfactory<tchannel> (endpointconfigurationname);
22:lock (Synchelper)
23: {
24:channelfactories[endpointconfigurationname] = ChannelFactory;
25:}
26:}
27:return ChannelFactory;
28:}
29:
30:public static void Invoke<tchannel> (Action<tchannel> Action, TChannel proxy)
31: {
32:icommunicationobject channel = proxy as Icommunicationobject;
33:if (NULL = = Channel)
34: {
35:throw New ArgumentException ("The proxy isn't a valid channel implementing the Icommunicationobject in Terface "," proxy ");
36:}
37:try
38: {
39:action (proxy);
40:}
41:catch (TimeoutException)
42: {
43:channel. Abort ();
44:throw;
45:}
46:catch (communicationexception)
47: {
48:channel. Abort ();
49:throw;
50:}
51:finally
52: {
53:channel. Close ();
54:}
55:}
56:
57:public static TResult Invoke<tchannel, tresult> (Func<tchannel, tresult> function, TChannel proxy)
58: {
59:icommunicationobject channel = proxy as Icommunicationobject;
60:if (NULL = = Channel)
61: {
62:throw New ArgumentException ("The proxy isn't a valid channel implementing the Icommunicationobject in Terface "," proxy ");
63:}
64:try
65: {
66:return function (proxy);
67:}
68:catch (TimeoutException)
69: {
70:channel. Abort ();
71:throw;
72:}
73:catch (communicationexception)
74: {
75:channel. Abort ();
76:throw;
77:}
78:finally
79: {
80:channel. Close ();
81:}
82:}
83:
84:public static void Invoke<tchannel> (Action<tchannel> Action, String endpointconfigurationname)
85: {
86:guard.argumentnotnullorempty (Endpointconfigurationname, "endpointconfigurationname");
87:invoke<tchannel> (Action, getchannelfactory<tchannel> (Endpointconfigurationname). CreateChannel ());
88:}
89:
90:public static TResult Invoke<tchannel, tresult> (Func<tchannel, tresult> function, String ENDPOINTC Onfigurationname)
91: {
92:guard.argumentnotnullorempty (Endpointconfigurationname, "endpointconfigurationname");
93:return Invoke<tchannel, tresult> (function, getchannelfactory<tchannel> (Endpointconfigurationna Me). CreateChannel ());
94:}
95:}
96:}

In the performance of the consideration, to avoid the frequent creation of channelfactory<tchannel>, through a Dictionary object will be created by the channelfactory<tchannel> cache; in two invoke methods, The invocation of the service is represented by two delegate objects (Action<tchannel> and Func<tchannel, tresult>), and another parameter represents the configuration name of the endpoint. Then the service invocation becomes quite simple:

   1:using System;
2:using Artech.Lib;
3:using Artech.WcfServices.Contracts;
4:namespace Artech.WcfServices.Clients
5: {
6: Class Program
7: {
8: static void Main (string[] args)
9: {
int result = Serviceinvoker.invoke<icalculator, int> (Calculator => calculator. ADD (1, 2), "CalculatorService");
One: Console.WriteLine ("x + y = {2} when x = {0} and y = {1}", 1, 2, result);
A: console.read ();
: }
: }
15:}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.