[sgen] Fix function signature
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / ServiceHostBase.cs
1 //
2 // ServiceHostBase.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //
7 // Copyright (C) 2005-2006 Novell, Inc.  http://www.novell.com
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Linq;
32 using System.ServiceModel.Channels;
33 using System.ServiceModel.Configuration;
34 using System.ServiceModel.Description;
35 using System.ServiceModel.Dispatcher;
36 using System.ServiceModel.Security;
37 using System.Reflection;
38 using System.Threading;
39
40 namespace System.ServiceModel
41 {
42         public abstract partial class ServiceHostBase
43                 : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
44         {
45                 // It is used for mapping a ServiceHostBase to HttpChannelListener precisely.
46                 internal static ServiceHostBase CurrentServiceHostHack;
47
48                 ServiceCredentials credentials;
49                 ServiceDescription description;
50                 UriSchemeKeyedCollection base_addresses;
51                 TimeSpan open_timeout, close_timeout, instance_idle_timeout;
52                 List<InstanceContext> contexts;
53                 ReadOnlyCollection<InstanceContext> exposed_contexts;
54                 ChannelDispatcherCollection channel_dispatchers;
55                 IDictionary<string,ContractDescription> contracts;
56                 int flow_limit = int.MaxValue;
57                 IExtensionCollection<ServiceHostBase> extensions;
58
59                 protected ServiceHostBase ()
60                 {
61                         open_timeout = DefaultOpenTimeout;
62                         close_timeout = DefaultCloseTimeout;
63
64                         credentials = new ServiceCredentials ();
65                         contexts = new List<InstanceContext> ();
66                         exposed_contexts = new ReadOnlyCollection<InstanceContext> (contexts);
67                         channel_dispatchers = new ChannelDispatcherCollection (this);
68                 }
69
70                 public event EventHandler<UnknownMessageReceivedEventArgs>
71                         UnknownMessageReceived;
72
73                 internal void OnUnknownMessageReceived (Message message)
74                 {
75                         if (UnknownMessageReceived != null)
76                                 UnknownMessageReceived (this, new UnknownMessageReceivedEventArgs (message));
77                         else
78                                 // FIXME: better be logged
79                                 throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' with action '{1}' which is not reachable in this service contract", message.Headers.To, message.Headers.Action));
80                 }
81
82                 public ReadOnlyCollection<Uri> BaseAddresses {
83                         get {
84                                 if (base_addresses == null)
85                                         base_addresses = new UriSchemeKeyedCollection ();
86                                 return new ReadOnlyCollection<Uri> (base_addresses.InternalItems);
87                         }
88                 }
89
90                 internal Uri CreateUri (string scheme, Uri relativeUri)
91                 {
92                         Uri baseUri = base_addresses.Contains (scheme) ? base_addresses [scheme] : null;
93
94                         if (relativeUri == null)
95                                 return baseUri;
96                         if (relativeUri.IsAbsoluteUri)
97                                 return relativeUri;
98                         if (baseUri == null)
99                                 return null;
100                         var s = relativeUri.ToString ();
101                         if (s.Length == 0)
102                                 return baseUri;
103                         var l = baseUri.LocalPath;
104                         var r = relativeUri.ToString ();
105
106                         if (l.Length > 0 && l [l.Length - 1] != '/' && r [0] != '/')
107                                 return new Uri (String.Concat (baseUri.ToString (), "/", r));
108                         else
109                                 return new Uri (String.Concat (baseUri.ToString (), r));
110                 }
111
112                 public ChannelDispatcherCollection ChannelDispatchers {
113                         get { return channel_dispatchers; }
114                 }
115
116                 public ServiceAuthorizationBehavior Authorization {
117                         get;
118                         private set;
119                 }
120
121                 public ServiceCredentials Credentials {
122                         get { return credentials; }
123                 }
124
125                 public ServiceDescription Description {
126                         get { return description; }
127                 }
128
129                 protected internal IDictionary<string,ContractDescription> ImplementedContracts {
130                         get { return contracts; }
131                 }
132
133                 public IExtensionCollection<ServiceHostBase> Extensions {
134                         get {
135                                 if (extensions == null)
136                                         extensions = new ExtensionCollection<ServiceHostBase> (this);
137                                 return extensions;
138                         }
139                 }
140
141                 protected internal override TimeSpan DefaultCloseTimeout {
142                         get { return DefaultCommunicationTimeouts.Instance.CloseTimeout; }
143                 }
144
145                 protected internal override TimeSpan DefaultOpenTimeout {
146                         get { return DefaultCommunicationTimeouts.Instance.OpenTimeout; }
147                 }
148
149                 public TimeSpan CloseTimeout {
150                         get { return close_timeout; }
151                         set { close_timeout = value; }
152                 }
153
154                 public TimeSpan OpenTimeout {
155                         get { return open_timeout; }
156                         set { open_timeout = value; }
157                 }
158
159                 public int ManualFlowControlLimit {
160                         get { return flow_limit; }
161                         set { flow_limit = value; }
162                 }
163
164                 protected void AddBaseAddress (Uri baseAddress)
165                 {
166                         if (base_addresses == null)
167                                 throw new InvalidOperationException ("Base addresses must be added before the service description is initialized");
168                         base_addresses.Add (baseAddress);
169                 }
170
171                 public ServiceEndpoint AddServiceEndpoint (
172                         string implementedContract, Binding binding, string address)
173                 {
174                         return AddServiceEndpoint (implementedContract,
175                                 binding,
176                                 new Uri (address, UriKind.RelativeOrAbsolute));
177                 }
178
179                 public ServiceEndpoint AddServiceEndpoint (
180                         string implementedContract, Binding binding,
181                         string address, Uri listenUri)
182                 {
183                         Uri uri = new Uri (address, UriKind.RelativeOrAbsolute);
184                         return AddServiceEndpoint (
185                                 implementedContract, binding, uri, listenUri);
186                 }
187
188                 public ServiceEndpoint AddServiceEndpoint (
189                         string implementedContract, Binding binding,
190                         Uri address)
191                 {
192                         return AddServiceEndpoint (implementedContract, binding, address, null);
193                 }
194
195                 public ServiceEndpoint AddServiceEndpoint (
196                         string implementedContract, Binding binding,
197                         Uri address, Uri listenUri)
198                 {
199                         EndpointAddress ea = new EndpointAddress (BuildAbsoluteUri (address, binding));
200                         ContractDescription cd = GetContract (implementedContract, binding.Namespace == "http://schemas.microsoft.com/ws/2005/02/mex/bindings");
201                         if (cd == null)
202                                 throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
203                         return AddServiceEndpointCore (cd, binding, ea, listenUri);
204                 }
205
206                 public virtual void AddServiceEndpoint (ServiceEndpoint endpoint)
207                 {
208                         if (endpoint == null)
209                                 throw new ArgumentNullException ("endpoint");
210
211                         ThrowIfDisposedOrImmutable ();
212
213                         if (endpoint.Address == null)
214                                 throw new ArgumentException ("Address on the argument endpoint is null");
215                         if (endpoint.Contract == null)
216                                 throw new ArgumentException ("Contract on the argument endpoint is null");
217                         if (endpoint.Binding == null)
218                                 throw new ArgumentException ("Binding on the argument endpoint is null");
219
220                         if (!ImplementedContracts.Values.Any (cd => cd.ContractType == endpoint.Contract.ContractType) &&
221                             endpoint.Binding.Namespace != "http://schemas.microsoft.com/ws/2005/02/mex/bindings") // special case
222                                 throw new InvalidOperationException (String.Format ("Contract '{0}' is not implemented in this service '{1}'", endpoint.Contract.Name, Description.Name));
223
224                         Description.Endpoints.Add (endpoint);
225                 }
226
227                 Type PopulateType (string typeName)
228                 {
229                         Type type = Type.GetType (typeName);
230                         if (type != null)
231                                 return type;
232                         foreach (ContractDescription cd in ImplementedContracts.Values) {
233                                 type = cd.ContractType.Assembly.GetType (typeName);
234                                 if (type != null)
235                                         return type;
236                         }
237                         return null;
238                 }
239
240                 ContractDescription mex_contract, help_page_contract;
241
242                 ContractDescription GetContract (string name, bool mexBinding)
243                 {
244                         // FIXME: not sure if they should really be special cases.
245                         switch (name) {
246                         case "IHttpGetHelpPageAndMetadataContract":
247                                 if (help_page_contract == null)
248                                         help_page_contract = ContractDescription.GetContract (typeof (IHttpGetHelpPageAndMetadataContract));
249                                 return help_page_contract;
250                         case "IMetadataExchange":
251                                 // this is certainly looking special (or we may 
252                                 // be missing something around ServiceMetadataExtension).
253                                 // It seems .NET WCF has some "infrastructure"
254                                 // endpoints. .NET ServiceHost fails to Open()
255                                 // if it was added only IMetadataExchange 
256                                 // endpoint (and you'll see the word
257                                 // "infrastructure" in the exception message).
258                                 if (mexBinding && Description.Behaviors.Find<ServiceMetadataBehavior> () == null)
259                                         break;
260                                 if (mex_contract == null)
261                                         mex_contract = ContractDescription.GetContract (typeof (IMetadataExchange));
262                                 return mex_contract;
263                         }
264
265                         Type type = PopulateType (name);
266                         if (type == null)
267                                 return null;
268
269                         foreach (ContractDescription cd in ImplementedContracts.Values) {
270                                 // This check is a negative side effect of the above match-by-name design.
271                                 if (cd.ContractType == typeof (IMetadataExchange))
272                                         continue;
273
274                                 if (cd.ContractType == type ||
275                                     cd.ContractType.IsSubclassOf (type) ||
276                                     type.IsInterface && cd.ContractType.GetInterface (type.FullName) == type)
277                                         return cd;
278                         }
279                         return null;
280                 }
281
282                 internal Uri BuildAbsoluteUri (Uri address, Binding binding)
283                 {
284                         if (!address.IsAbsoluteUri) {
285                                 // Find a Base address with matching scheme,
286                                 // and build new absolute address
287                                 if (!base_addresses.Contains (binding.Scheme))
288                                         throw new InvalidOperationException (String.Format ("Could not find base address that matches Scheme {0} for endpoint {1}", binding.Scheme, binding.Name));
289
290                                 Uri baseaddr = base_addresses [binding.Scheme];
291
292                                 if (!baseaddr.AbsoluteUri.EndsWith ("/") && address.OriginalString.Length > 0) // with empty URI it should not add '/' to possible file name of the absolute URI
293                                         baseaddr = new Uri (baseaddr.AbsoluteUri + "/");
294                                 address = new Uri (baseaddr, address);
295                         }
296                         return address;
297                 }
298
299                 internal ServiceEndpoint AddServiceEndpointCore (
300                         ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
301                 {
302                         if (listenUri != null)
303                                 listenUri = BuildAbsoluteUri (listenUri, binding);
304
305                         foreach (ServiceEndpoint e in Description.Endpoints)
306                                 if (e.Contract == cd && e.Binding == binding && e.Address == address && e.ListenUri.Equals (listenUri))
307                                         return e;
308                         ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
309                         // FIXME: should we reject relative ListenUri?
310                         se.ListenUri = listenUri ?? address.Uri;
311                         Description.Endpoints.Add (se);
312                         return se;
313                 }
314
315                 protected virtual void ApplyConfiguration ()
316                 {
317                         if (Description == null)
318                                 throw new InvalidOperationException ("ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation");
319
320                         ServiceElement service = GetServiceElement ();
321                         
322                         if (service != null)
323                                 LoadConfigurationSection (service);
324                         // simplified configuration
325                         AddServiceBehaviors (String.Empty, false);
326                         // TODO: consider commonBehaviors here
327
328                         // ensure ServiceAuthorizationBehavior
329                         Authorization = Description.Behaviors.Find<ServiceAuthorizationBehavior> ();
330                         if (Authorization == null) {
331                                 Authorization = new ServiceAuthorizationBehavior ();
332                                 Description.Behaviors.Add (Authorization);
333                         }
334
335                         // ensure ServiceDebugBehavior
336                         ServiceDebugBehavior debugBehavior = Description.Behaviors.Find<ServiceDebugBehavior> ();
337                         if (debugBehavior == null) {
338                                 debugBehavior = new ServiceDebugBehavior ();
339                                 Description.Behaviors.Add (debugBehavior);
340                         }
341                 }
342
343                 void AddServiceBehaviors (string configurationName, bool throwIfNotFound)
344                 {
345                         if (configurationName == null)
346                                 return;
347                         ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors [configurationName];
348                         if (behavior == null) {
349                                 if (throwIfNotFound)
350                                         throw new ArgumentException (String.Format ("Service behavior configuration '{0}' was not found", configurationName));
351                                 return;
352                         }
353
354                         KeyedByTypeCollection<IServiceBehavior> behaviors = Description.Behaviors;
355                         foreach (var bxe in behavior) {
356                                 IServiceBehavior b = (IServiceBehavior) bxe.CreateBehavior ();
357                                 if (behaviors.Contains (b.GetType ()))
358                                         continue;
359                                 behaviors.Add (b);
360                         }
361                 }
362                 
363                 void ApplyServiceElement (ServiceElement service)
364                 {
365                         //base addresses
366                         HostElement host = service.Host;
367                         foreach (BaseAddressElement baseAddress in host.BaseAddresses) {
368                                 AddBaseAddress (new Uri (baseAddress.BaseAddress));
369                         }
370
371                         // behaviors
372                         AddServiceBehaviors (service.BehaviorConfiguration, true);
373
374                         // endpoints
375                         foreach (ServiceEndpointElement endpoint in service.Endpoints) {
376                                 ServiceEndpoint se;
377
378                                 var binding = String.IsNullOrEmpty (endpoint.Binding) ? null : ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
379
380                                 if (!String.IsNullOrEmpty (endpoint.Kind)) {
381                                         var contract = String.IsNullOrEmpty (endpoint.Contract) ? null : GetContract (endpoint.Contract, false);
382                                         se = ConfigUtil.ConfigureStandardEndpoint (contract, endpoint);
383                                         if (se.Binding == null)
384                                                 se.Binding = binding;
385                                         if (se.Address == null && se.Binding != null) // standard endpoint might have empty address
386                                                 se.Address = new EndpointAddress (CreateUri (se.Binding.Scheme, endpoint.Address));
387                                         if (se.Binding == null && se.Address != null) // look for protocol mapping
388                                                 se.Binding = ConfigUtil.GetBindingByProtocolMapping (se.Address.Uri);
389
390                                         AddServiceEndpoint (se);
391                                 }
392                                 else {
393                                         if (binding == null && endpoint.Address != null) // look for protocol mapping
394                                                 binding = ConfigUtil.GetBindingByProtocolMapping (endpoint.Address);
395                                         se = AddServiceEndpoint (endpoint.Contract, binding, endpoint.Address);
396                                 }
397
398                                 // endpoint behaviors
399                                 EndpointBehaviorElement epbehavior = ConfigUtil.BehaviorsSection.EndpointBehaviors [endpoint.BehaviorConfiguration];
400                                 if (epbehavior != null)
401                                         foreach (var bxe in epbehavior) {
402                                                 IEndpointBehavior b = (IEndpointBehavior) bxe.CreateBehavior ();
403                                                 se.Behaviors.Add (b);
404                                 }
405                         }
406                 }
407
408                 private ServiceElement GetServiceElement() {
409                         Type serviceType = Description.ServiceType;
410                         if (serviceType == null)
411                                 return null;
412
413                         return ConfigUtil.ServicesSection.Services [serviceType.FullName];                      
414                 }
415
416                 protected abstract ServiceDescription CreateDescription (
417                         out IDictionary<string,ContractDescription> implementedContracts);
418
419                 protected void InitializeDescription (UriSchemeKeyedCollection baseAddresses)
420                 {
421                         this.base_addresses = baseAddresses;
422                         IDictionary<string,ContractDescription> retContracts;
423                         description = CreateDescription (out retContracts);
424                         contracts = retContracts;
425
426                         ApplyConfiguration ();
427                 }
428
429                 protected virtual void InitializeRuntime ()
430                 {
431                         //First validate the description, which should call all behaviors
432                         //'Validate' method.
433                         ValidateDescription ();
434                         
435                         //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
436                         //We must keep thet ServiceEndpoints as a seperate collection, since the user
437                         //can change the collection in the description during the behaviors events.
438                         ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
439                         Description.Endpoints.CopyTo (endPoints, 0);
440                         var builder = new DispatcherBuilder (this);
441                         foreach (ServiceEndpoint se in endPoints) {
442                                 var commonParams = new BindingParameterCollection ();
443                                 foreach (IServiceBehavior b in Description.Behaviors)
444                                         b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
445
446                                 var channel = builder.BuildChannelDispatcher (Description.ServiceType, se, commonParams);
447                                 if (!ChannelDispatchers.Contains (channel))
448                                         ChannelDispatchers.Add (channel);
449                         }
450
451                         //After the ChannelDispatchers are created, and attached to the service host
452                         //Apply dispatching behaviors.
453                         //
454                         // This behavior application order is tricky: first only
455                         // ServiceDebugBehavior and ServiceMetadataBehavior are
456                         // applied, and then other service behaviors are applied.
457                         // It is because those two behaviors adds ChannelDispatchers
458                         // and any other service behaviors must be applied to
459                         // those newly populated dispatchers.
460                         foreach (IServiceBehavior b in Description.Behaviors)
461                                 if (b is ServiceMetadataBehavior || b is ServiceDebugBehavior)
462                                         b.ApplyDispatchBehavior (Description, this);
463                         foreach (IServiceBehavior b in Description.Behaviors)
464                                 if (!(b is ServiceMetadataBehavior || b is ServiceDebugBehavior))
465                                         b.ApplyDispatchBehavior (Description, this);
466
467                         builder.ApplyDispatchBehaviors ();
468                 }
469
470                 private void ValidateDescription ()
471                 {
472                         foreach (IServiceBehavior b in Description.Behaviors)
473                                 b.Validate (Description, this);
474                         foreach (ServiceEndpoint endPoint in Description.Endpoints)
475                                 endPoint.Validate ();
476
477                         // In 4.0, it seems that if there is no configured ServiceEndpoint, infer them from the service type.
478                         if (Description.Endpoints.Count == 0) {
479                                 foreach (Type iface in Description.ServiceType.GetInterfaces ())
480                                         if (iface.GetCustomAttributes (typeof (ServiceContractAttribute), true).Length > 0)
481                                                 foreach (var baddr in BaseAddresses) {
482                                                         if (!baddr.IsAbsoluteUri)
483                                                                 continue;
484                                                         var binding = ConfigUtil.GetBindingByProtocolMapping (baddr);
485                                                         if (binding == null)
486                                                                 continue;
487                                                         AddServiceEndpoint (iface.FullName, binding, baddr);
488                                                 }
489                         }
490
491                         if (Description.Endpoints.FirstOrDefault (e => e.Contract != mex_contract && !e.IsSystemEndpoint) == null)
492                                 throw new InvalidOperationException ("The ServiceHost must have at least one application endpoint (that does not include metadata exchange endpoint) defined by either configuration, behaviors or call to AddServiceEndpoint methods.");
493                 }
494
495                 protected void LoadConfigurationSection (ServiceElement serviceSection)
496                 {
497                         ApplyServiceElement (serviceSection);
498                 }
499
500                 protected override sealed void OnAbort ()
501                 {
502                         OnCloseOrAbort (TimeSpan.Zero);
503                 }
504
505                 Action<TimeSpan> close_delegate;
506                 Action<TimeSpan> open_delegate;
507
508                 protected override sealed IAsyncResult OnBeginClose (
509                         TimeSpan timeout, AsyncCallback callback, object state)
510                 {
511                         if (close_delegate != null)
512                                 close_delegate = new Action<TimeSpan> (OnClose);
513                         return close_delegate.BeginInvoke (timeout, callback, state);
514                 }
515
516                 protected override sealed IAsyncResult OnBeginOpen (
517                         TimeSpan timeout, AsyncCallback callback, object state)
518                 {
519                         if (open_delegate == null)
520                                 open_delegate = new Action<TimeSpan> (OnOpen);
521                         return open_delegate.BeginInvoke (timeout, callback, state);
522                 }
523
524                 protected override void OnClose (TimeSpan timeout)
525                 {
526                         OnCloseOrAbort (timeout);
527                 }
528                 
529                 void OnCloseOrAbort (TimeSpan timeout)
530                 {
531                         DateTime start = DateTime.Now;
532                         ReleasePerformanceCounters ();
533                         List<ChannelDispatcherBase> l = new List<ChannelDispatcherBase> (ChannelDispatchers);
534                         foreach (ChannelDispatcherBase e in l) {
535                                 try {
536                                         TimeSpan ts = timeout - (DateTime.Now - start);
537                                         if (ts < TimeSpan.Zero)
538                                                 e.Abort ();
539                                         else
540                                                 e.Close (ts);
541                                 } catch (Exception ex) {
542                                         Console.WriteLine ("ServiceHostBase failed to close the channel dispatcher:");
543                                         Console.WriteLine (ex);
544                                 }
545                         }
546                 }
547
548                 protected override sealed void OnOpen (TimeSpan timeout)
549                 {
550                         DateTime start = DateTime.Now;
551                         InitializeRuntime ();
552                         for (int i = 0; i < ChannelDispatchers.Count; i++) {
553                                 // Skip ServiceMetadataExtension-based one. special case.
554                                 for (int j = i + 1; j < ChannelDispatchers.Count; j++) {
555                                         var cd1 = ChannelDispatchers [i];
556                                         var cd2 = ChannelDispatchers [j];
557                                         if (cd1.IsMex || cd2.IsMex)
558                                                 continue;
559                                         // surprisingly, some ChannelDispatcherBase implementations have null Listener property.
560                                         if (cd1.Listener != null && cd2.Listener != null && cd1.Listener.Uri.Equals (cd2.Listener.Uri))
561                                                 throw new InvalidOperationException ("Two or more service endpoints with different Binding instance are bound to the same listen URI.");
562                                 }
563                         }
564
565                         var waits = new List<ManualResetEvent> ();
566                         foreach (var cd in ChannelDispatchers) {
567                                 var wait = new ManualResetEvent (false);
568                                 cd.Opened += delegate { wait.Set (); };
569                                 waits.Add (wait);
570                                 cd.Open (timeout - (DateTime.Now - start));
571                         }
572
573                         WaitHandle.WaitAll (waits.ToArray ());
574                 }
575
576                 protected override void OnEndClose (IAsyncResult result)
577                 {
578                         if (close_delegate == null)
579                                 throw new InvalidOperationException ("Async close operation has not started");
580                         close_delegate.EndInvoke (result);
581                 }
582
583                 protected override sealed void OnEndOpen (IAsyncResult result)
584                 {
585                         if (open_delegate == null)
586                                 throw new InvalidOperationException ("Aync open operation has not started");
587                         open_delegate.EndInvoke (result);
588                 }
589
590                 protected override void OnOpened ()
591                 {
592                         base.OnOpened ();
593                 }
594
595                 [MonoTODO]
596                 protected void ReleasePerformanceCounters ()
597                 {
598                 }
599
600                 void IDisposable.Dispose ()
601                 {
602                         Close ();
603                 }
604         }
605
606         /// <summary>
607         ///  Builds ChannelDispatchers as appropriate to service the service endpoints. 
608         /// </summary>
609         partial class DispatcherBuilder
610         {
611                 ServiceHostBase host;
612
613                 public DispatcherBuilder (ServiceHostBase host)
614                 {
615                         this.host = host;
616                 }
617
618                 Dictionary<Binding,ChannelDispatcher> built_dispatchers = new Dictionary<Binding,ChannelDispatcher> ();
619                 Dictionary<ServiceEndpoint, EndpointDispatcher> ep_to_dispatcher_ep = new Dictionary<ServiceEndpoint, EndpointDispatcher> ();
620
621                 internal static Action<ChannelDispatcher> ChannelDispatcherSetter;
622
623                 internal ChannelDispatcher BuildChannelDispatcher (Type serviceType, ServiceEndpoint se, BindingParameterCollection commonParams)
624                 {
625                         //Let all behaviors add their binding parameters
626                         AddBindingParameters (commonParams, se);
627                         
628                         // See if there's an existing channel that matches this endpoint
629                         var version = se.Binding.GetProperty<MessageVersion> (commonParams);
630                         if (version == null)
631                                 throw new InvalidOperationException ("At least one BindingElement in the Binding must override GetProperty method to return a MessageVersion and no prior binding element should return null instead of calling GetInnerProperty method on BindingContext.");
632
633                         ChannelDispatcher cd = FindExistingDispatcher (se);
634                         EndpointDispatcher ep;
635                         if (cd != null) {
636                                 ep = cd.InitializeServiceEndpoint (serviceType, se);
637                         } else {
638                                 // Use the binding parameters to build the channel listener and Dispatcher.
639                                 lock (HttpTransportBindingElement.ListenerBuildLock) {
640                                         ServiceHostBase.CurrentServiceHostHack = host;
641                                         IChannelListener lf = BuildListener (se, commonParams);
642                                         cd = new ChannelDispatcher (lf, se.Binding.Name);
643                                         cd.MessageVersion = version;
644                                         if (ChannelDispatcherSetter != null) {
645                                                 ChannelDispatcherSetter (cd);
646                                                 ChannelDispatcherSetter = null;
647                                         }
648                                         ServiceHostBase.CurrentServiceHostHack = null;
649                                 }
650                                 ep = cd.InitializeServiceEndpoint (serviceType, se);
651                                 built_dispatchers.Add (se.Binding, cd);
652                         }
653                         ep_to_dispatcher_ep[se] = ep;
654                         return cd;
655                 }
656                 
657                 ChannelDispatcher FindExistingDispatcher (ServiceEndpoint se)
658                 {
659                         return built_dispatchers.FirstOrDefault ((KeyValuePair<Binding,ChannelDispatcher> p) => se.Binding == p.Key).Value;
660                 }
661
662                 internal void ApplyDispatchBehaviors ()
663                 {
664                         foreach (KeyValuePair<ServiceEndpoint, EndpointDispatcher> val in ep_to_dispatcher_ep)
665                                 ApplyDispatchBehavior (val.Value, val.Key);
666                 }
667                 
668                 private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
669                 {
670                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
671                                 b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
672                         foreach (IEndpointBehavior b in endPoint.Behaviors)
673                                 b.ApplyDispatchBehavior (endPoint, ed);
674                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
675                                 if (operation.InCallbackContract)
676                                         continue; // irrelevant
677                                 foreach (IOperationBehavior b in operation.Behaviors)
678                                         b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
679                         }
680
681                 }
682
683                 private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
684
685                         commonParams.Add (ChannelProtectionRequirements.CreateFromContract (endPoint.Contract));
686
687                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
688                                 b.AddBindingParameters (endPoint.Contract, endPoint, commonParams);
689                         foreach (IEndpointBehavior b in endPoint.Behaviors)
690                                 b.AddBindingParameters (endPoint, commonParams);
691                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
692                                 foreach (IOperationBehavior b in operation.Behaviors)
693                                         b.AddBindingParameters (operation, commonParams);
694                         }
695                 }
696
697                 static IChannelListener BuildListener (ServiceEndpoint se,
698                         BindingParameterCollection pl)
699                 {
700                         Binding b = se.Binding;
701                         if (b.CanBuildChannelListener<IReplySessionChannel> (pl))
702                                 return b.BuildChannelListener<IReplySessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
703                         if (b.CanBuildChannelListener<IReplyChannel> (pl))
704                                 return b.BuildChannelListener<IReplyChannel> (se.ListenUri, "", se.ListenUriMode, pl);
705                         if (b.CanBuildChannelListener<IInputSessionChannel> (pl))
706                                 return b.BuildChannelListener<IInputSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
707                         if (b.CanBuildChannelListener<IInputChannel> (pl))
708                                 return b.BuildChannelListener<IInputChannel> (se.ListenUri, "", se.ListenUriMode, pl);
709
710                         if (b.CanBuildChannelListener<IDuplexChannel> (pl))
711                                 return b.BuildChannelListener<IDuplexChannel> (se.ListenUri, "", se.ListenUriMode, pl);
712                         if (b.CanBuildChannelListener<IDuplexSessionChannel> (pl))
713                                 return b.BuildChannelListener<IDuplexSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
714                         throw new InvalidOperationException ("None of the listener channel types is supported");
715                 }
716         }
717 }