2009-09-11 Atsushi Enomoto <atsushi@ximian.com>
[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.ServiceModel.Channels;
32 using System.ServiceModel.Configuration;
33 using System.ServiceModel.Description;
34 using System.ServiceModel.Dispatcher;
35 using System.ServiceModel.Security;
36 using System.Reflection;
37
38 namespace System.ServiceModel
39 {
40         public abstract partial class ServiceHostBase
41                 : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
42         {
43                 ServiceCredentials credentials;
44                 ServiceDescription description;
45                 UriSchemeKeyedCollection base_addresses;
46                 TimeSpan open_timeout, close_timeout, instance_idle_timeout;
47                 ServiceThrottle throttle;
48                 List<InstanceContext> contexts;
49                 ReadOnlyCollection<InstanceContext> exposed_contexts;
50                 ChannelDispatcherCollection channel_dispatchers;
51                 IDictionary<string,ContractDescription> contracts;
52                 int flow_limit = int.MaxValue;
53                 IExtensionCollection<ServiceHostBase> extensions;
54
55                 protected ServiceHostBase ()
56                 {
57                         open_timeout = DefaultOpenTimeout;
58                         close_timeout = DefaultCloseTimeout;
59
60                         credentials = new ServiceCredentials ();
61                         throttle = new ServiceThrottle ();
62                         contexts = new List<InstanceContext> ();
63                         exposed_contexts = new ReadOnlyCollection<InstanceContext> (contexts);
64                         channel_dispatchers = new ChannelDispatcherCollection (this);
65                 }
66
67                 public event EventHandler<UnknownMessageReceivedEventArgs>
68                         UnknownMessageReceived;
69
70                 internal void OnUnknownMessageReceived (Message message)
71                 {
72                         if (UnknownMessageReceived != null)
73                                 UnknownMessageReceived (this, new UnknownMessageReceivedEventArgs (message));
74                         else
75                                 // FIXME: better be logged
76                                 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));
77                 }
78
79                 public ReadOnlyCollection<Uri> BaseAddresses {
80                         get {
81                                 if (base_addresses == null)
82                                         base_addresses = new UriSchemeKeyedCollection ();
83                                 return new ReadOnlyCollection<Uri> (base_addresses.InternalItems);
84                         }
85                 }
86
87                 internal Uri CreateUri (string sheme, Uri relatieUri) {
88                         Uri baseUri = base_addresses.Contains (sheme) ? base_addresses [sheme] : null;
89
90                         if (relatieUri == null)
91                                 return baseUri;
92                         if (relatieUri.IsAbsoluteUri)
93                                 return relatieUri;
94                         if (baseUri == null)
95                                 return null;
96                         return new Uri (baseUri, relatieUri);
97                 }
98
99                 public ChannelDispatcherCollection ChannelDispatchers {
100                         get { return channel_dispatchers; }
101                 }
102
103                 public ServiceAuthorizationBehavior Authorization {
104                         get;
105                         private set;
106                 }
107
108                 [MonoTODO]
109                 public ServiceCredentials Credentials {
110                         get { return credentials; }
111                 }
112
113                 public ServiceDescription Description {
114                         get { return description; }
115                 }
116
117                 protected IDictionary<string,ContractDescription> ImplementedContracts {
118                         get { return contracts; }
119                 }
120
121                 [MonoTODO]
122                 public IExtensionCollection<ServiceHostBase> Extensions {
123                         get {
124                                 if (extensions == null)
125                                         extensions = new ExtensionCollection<ServiceHostBase> (this);
126                                 return extensions;
127                         }
128                 }
129
130                 protected internal override TimeSpan DefaultCloseTimeout {
131                         get { return DefaultCommunicationTimeouts.Instance.CloseTimeout; }
132                 }
133
134                 protected internal override TimeSpan DefaultOpenTimeout {
135                         get { return DefaultCommunicationTimeouts.Instance.OpenTimeout; }
136                 }
137
138                 public TimeSpan CloseTimeout {
139                         get { return close_timeout; }
140                         set { close_timeout = value; }
141                 }
142
143                 public TimeSpan OpenTimeout {
144                         get { return open_timeout; }
145                         set { open_timeout = value; }
146                 }
147
148                 public int ManualFlowControlLimit {
149                         get { return flow_limit; }
150                         set { flow_limit = value; }
151                 }
152
153                 protected void AddBaseAddress (Uri baseAddress)
154                 {
155                         if (Description != null)
156                                 throw new InvalidOperationException ("Base addresses must be added before the service description is initialized");
157                         base_addresses.Add (baseAddress);
158                 }
159
160                 public ServiceEndpoint AddServiceEndpoint (
161                         string implementedContract, Binding binding, string address)
162                 {
163                         return AddServiceEndpoint (implementedContract,
164                                 binding,
165                                 new Uri (address, UriKind.RelativeOrAbsolute));
166                 }
167
168                 public ServiceEndpoint AddServiceEndpoint (
169                         string implementedContract, Binding binding,
170                         string address, Uri listenUri)
171                 {
172                         Uri uri = new Uri (address, UriKind.RelativeOrAbsolute);
173                         return AddServiceEndpoint (
174                                 implementedContract, binding, uri, listenUri);
175                 }
176
177                 public ServiceEndpoint AddServiceEndpoint (
178                         string implementedContract, Binding binding,
179                         Uri address)
180                 {
181                         return AddServiceEndpoint (implementedContract, binding, address, address);
182                 }
183
184                 public ServiceEndpoint AddServiceEndpoint (
185                         string implementedContract, Binding binding,
186                         Uri address, Uri listenUri)
187                 {
188                         EndpointAddress ea = BuildEndpointAddress (address, binding);
189                         ContractDescription cd = GetContract (implementedContract);
190                         if (cd == null)
191                                 throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
192                         return AddServiceEndpointCore (cd, binding, ea, listenUri);
193                 }
194
195                 Type PopulateType (string typeName)
196                 {
197                         Type type = Type.GetType (typeName);
198                         if (type != null)
199                                 return type;
200                         foreach (ContractDescription cd in ImplementedContracts.Values) {
201                                 type = cd.ContractType.Assembly.GetType (typeName);
202                                 if (type != null)
203                                         return type;
204                         }
205                         return null;
206                 }
207
208                 ContractDescription GetContract (string name)
209                 {
210                         //FIXME: hack hack hack
211                         ImplementedContracts ["IHttpGetHelpPageAndMetadataContract"] =
212                                 ContractDescription.GetContract (typeof (IHttpGetHelpPageAndMetadataContract));
213
214                         // FIXME: As long as I tried, *only* IMetadataExchange
215                         // is the exception case that does not require full
216                         // type name. Hence I treat it as a special case.
217                         if (name == ServiceMetadataBehavior.MexContractName) {
218                                 if (!Description.Behaviors.Contains (typeof (ServiceMetadataBehavior)) && Array.IndexOf (Description.ServiceType.GetInterfaces (), typeof (IMetadataExchange)) < 0)
219                                         throw new InvalidOperationException (
220                                                 "Add ServiceMetadataBehavior to the ServiceHost to add a endpoint for IMetadataExchange contract.");
221                                         
222                                 ImplementedContracts [ServiceMetadataBehavior.MexContractName] =
223                                         ContractDescription.GetContract (typeof (IMetadataExchange));
224
225                                 foreach (ContractDescription cd in ImplementedContracts.Values)
226                                         if (cd.ContractType == typeof (IMetadataExchange))
227                                                 return cd;
228                                 return null;
229                         }
230
231                         Type type = PopulateType (name);
232
233                         foreach (ContractDescription cd in ImplementedContracts.Values) {
234                                 // FIXME: This check is a negative side effect 
235                                 // of the above hack.
236                                 if (cd.ContractType == typeof (IMetadataExchange))
237                                         continue;
238
239                                 if (type == null) {
240                                         if (cd.Name == name)
241                                                 return cd;
242                                         continue;
243                                 }
244
245                                 if (cd.ContractType == type ||
246                                     cd.ContractType.IsSubclassOf (type) ||
247                                     type.IsInterface && cd.ContractType.GetInterface (type.FullName) == type)
248                                         return cd;
249                         }
250                         return null;
251                 }
252
253                 internal EndpointAddress BuildEndpointAddress (Uri address, Binding binding)
254                 {
255                         if (!address.IsAbsoluteUri) {
256                                 // Find a Base address with matching scheme,
257                                 // and build new absolute address
258                                 if (!base_addresses.Contains (binding.Scheme))
259                                         throw new InvalidOperationException (String.Format ("Could not find base address that matches Scheme {0} for endpoint {1}", binding.Scheme, binding.Name));
260
261                                 Uri baseaddr = base_addresses [binding.Scheme];
262
263                                 if (!baseaddr.AbsoluteUri.EndsWith ("/") && address.OriginalString.Length > 0) // with empty URI it should not add '/' to possible file name of the absolute URI
264                                         baseaddr = new Uri (baseaddr.AbsoluteUri + "/");
265                                 address = new Uri (baseaddr, address);
266                         }
267                         return new EndpointAddress (address);
268                 }
269
270                 internal ServiceEndpoint AddServiceEndpointCore (
271                         ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
272                 {
273                         foreach (ServiceEndpoint e in Description.Endpoints)
274                                 if (e.Contract == cd)
275                                         return e;
276                         ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
277                         se.ListenUri = listenUri.IsAbsoluteUri ? listenUri : new Uri (address.Uri, listenUri);
278                         Description.Endpoints.Add (se);
279                         return se;
280                 }
281
282                 [MonoTODO]
283                 protected virtual void ApplyConfiguration ()
284                 {
285                         if (Description == null)
286                                 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");
287
288                         ServiceElement service = GetServiceElement ();
289
290                         //TODO: Should we call here LoadServiceElement ?
291                         if (service != null) {
292                                 
293                                 //base addresses
294                                 HostElement host = service.Host;
295                                 foreach (BaseAddressElement baseAddress in host.BaseAddresses) {
296                                         AddBaseAddress (new Uri (baseAddress.BaseAddress));
297                                 }
298
299                                 // services
300                                 foreach (ServiceEndpointElement endpoint in service.Endpoints) {
301                                         // FIXME: consider BindingName as well
302                                         ServiceEndpoint se = AddServiceEndpoint (
303                                                 endpoint.Contract,
304                                                 ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration),
305                                                 endpoint.Address.ToString ());
306                                 }
307                                 // behaviors
308                                 // TODO: use EvaluationContext of ServiceElement.
309                                 ServiceBehaviorElement behavior = ConfigUtil.BehaviorsSection.ServiceBehaviors.Find (service.BehaviorConfiguration);
310                                 if (behavior != null) {
311                                         for (int i = 0; i < behavior.Count; i++) {
312                                                 BehaviorExtensionElement bxel = behavior [i];
313                                                 IServiceBehavior b = (IServiceBehavior) behavior [i].CreateBehavior ();
314                                                 if (b != null)
315                                                         Description.Behaviors.Add (b);
316                                         }
317                                 }
318                         }
319                         // TODO: consider commonBehaviors here
320
321                         // ensure ServiceAuthorizationBehavior
322                         Authorization = Description.Behaviors.Find<ServiceAuthorizationBehavior> ();
323                         if (Authorization == null) {
324                                 Authorization = new ServiceAuthorizationBehavior ();
325                                 Description.Behaviors.Add (Authorization);
326                         }
327
328                         // ensure ServiceDebugBehavior
329                         ServiceDebugBehavior debugBehavior = Description.Behaviors.Find<ServiceDebugBehavior> ();
330                         if (debugBehavior == null) {
331                                 debugBehavior = new ServiceDebugBehavior ();
332                                 Description.Behaviors.Add (debugBehavior);
333                         }
334                 }
335
336                 private ServiceElement GetServiceElement() {
337                         Type serviceType = Description.ServiceType;
338                         if (serviceType == null)
339                                 return null;
340
341                         return ConfigUtil.ServicesSection.Services [serviceType.FullName];                      
342                 }
343
344                 internal ContractDescription GetContract (string name, string ns)
345                 {
346                         foreach (ContractDescription d in ImplementedContracts.Values)
347                                 if (d.Name == name && d.Namespace == ns)
348                                         return d;
349                         return null;
350                 }
351
352                 protected abstract ServiceDescription CreateDescription (
353                         out IDictionary<string,ContractDescription> implementedContracts);
354
355                 protected void InitializeDescription (UriSchemeKeyedCollection baseAddresses)
356                 {
357                         this.base_addresses = baseAddresses;
358                         IDictionary<string,ContractDescription> retContracts;
359                         description = CreateDescription (out retContracts);
360                         contracts = retContracts;
361
362                         ApplyConfiguration ();
363                 }
364
365                 protected virtual void InitializeRuntime ()
366                 {
367                         //First validate the description, which should call all behaviors
368                         //'Validate' method.
369                         ValidateDescription ();
370                         
371                         //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
372                         //We must keep thet ServiceEndpoints as a seperate collection, since the user
373                         //can change the collection in the description during the behaviors events.
374                         Dictionary<ServiceEndpoint, ChannelDispatcher> endPointToDispatcher = new Dictionary<ServiceEndpoint,ChannelDispatcher>();
375                         ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
376                         Description.Endpoints.CopyTo (endPoints, 0);
377                         foreach (ServiceEndpoint se in endPoints) {
378
379                                 var commonParams = new BindingParameterCollection ();
380                                 foreach (IServiceBehavior b in Description.Behaviors)
381                                         b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
382
383                                 ChannelDispatcher channel = BuildChannelDispatcher (se, commonParams);
384                                 ChannelDispatchers.Add (channel);
385                                 endPointToDispatcher[se] = channel;
386                         }
387
388                         //After the ChannelDispatchers are created, and attached to the service host
389                         //Apply dispatching behaviors.
390                         foreach (IServiceBehavior b in Description.Behaviors)
391                                 b.ApplyDispatchBehavior (Description, this);
392
393                         foreach(KeyValuePair<ServiceEndpoint, ChannelDispatcher> val in endPointToDispatcher)
394                                 foreach (var ed in val.Value.Endpoints)
395                                         ApplyDispatchBehavior (ed, val.Key);                    
396                 }
397
398                 private void ValidateDescription ()
399                 {
400                         foreach (IServiceBehavior b in Description.Behaviors)
401                                 b.Validate (Description, this);
402                         foreach (ServiceEndpoint endPoint in Description.Endpoints)
403                                 endPoint.Validate ();
404                 }               
405
406                 private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
407                 {
408                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
409                                 b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
410                         foreach (IEndpointBehavior b in endPoint.Behaviors)
411                                 b.ApplyDispatchBehavior (endPoint, ed);
412                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
413                                 foreach (IOperationBehavior b in operation.Behaviors)
414                                         b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
415                         }
416
417                 }
418
419                 internal ChannelDispatcher BuildChannelDispatcher (ServiceEndpoint se, BindingParameterCollection commonParams)
420                 {
421                         return new DispatcherBuilder ().BuildChannelDispatcher (Description.ServiceType, se, commonParams);
422                 }
423
424                 [MonoTODO]
425                 protected void LoadConfigurationSection (ServiceElement element)
426                 {
427                         ServicesSection services = ConfigUtil.ServicesSection;
428                 }
429
430                 void DoOpen (TimeSpan timeout)
431                 {
432                         foreach (var cd in ChannelDispatchers) {
433                                 cd.Open (timeout);
434                                 // This is likely hack.
435                                 if (cd is ChannelDispatcher)
436                                         ((ChannelDispatcher) cd).StartLoop ();
437                         }
438                 }
439
440                 [MonoTODO]
441                 protected override sealed void OnAbort ()
442                 {
443                 }
444
445                 Action<TimeSpan> close_delegate;
446                 Action<TimeSpan> open_delegate;
447
448                 protected override sealed IAsyncResult OnBeginClose (
449                         TimeSpan timeout, AsyncCallback callback, object state)
450                 {
451                         if (close_delegate != null)
452                                 close_delegate = new Action<TimeSpan> (OnClose);
453                         return close_delegate.BeginInvoke (timeout, callback, state);
454                 }
455
456                 protected override sealed IAsyncResult OnBeginOpen (
457                         TimeSpan timeout, AsyncCallback callback, object state)
458                 {
459                         if (open_delegate == null)
460                                 open_delegate = new Action<TimeSpan> (OnOpen);
461                         return open_delegate.BeginInvoke (timeout, callback, state);
462                 }
463
464                 protected override void OnClose (TimeSpan timeout)
465                 {
466                         DateTime start = DateTime.Now;
467                         ReleasePerformanceCounters ();
468                         List<ChannelDispatcherBase> l = new List<ChannelDispatcherBase> (ChannelDispatchers);
469                         foreach (ChannelDispatcherBase e in l) {
470                                 try {
471                                         TimeSpan ts = timeout - (DateTime.Now - start);
472                                         if (ts < TimeSpan.Zero)
473                                                 e.Abort ();
474                                         else
475                                                 e.Close (ts);
476                                 } catch (Exception ex) {
477                                         Console.WriteLine ("ServiceHostBase failed to close the channel dispatcher:");
478                                         Console.WriteLine (ex);
479                                 }
480                         }
481                 }
482
483                 protected override sealed void OnOpen (TimeSpan timeout)
484                 {
485                         InitializeRuntime ();
486                         DoOpen (timeout);
487                 }
488
489                 protected override void OnEndClose (IAsyncResult result)
490                 {
491                         if (close_delegate == null)
492                                 throw new InvalidOperationException ("Async close operation has not started");
493                         close_delegate.EndInvoke (result);
494                 }
495
496                 protected override sealed void OnEndOpen (IAsyncResult result)
497                 {
498                         if (open_delegate == null)
499                                 throw new InvalidOperationException ("Aync open operation has not started");
500                         open_delegate.EndInvoke (result);
501                 }
502
503                 protected override void OnOpened ()
504                 {
505                 }
506
507                 [MonoTODO]
508                 protected void ReleasePerformanceCounters ()
509                 {
510                 }
511
512                 void IDisposable.Dispose ()
513                 {
514                         Close ();
515                 }
516
517                 /*
518                 class SyncMethodInvoker : IOperationInvoker
519                 {
520                         readonly MethodInfo _methodInfo;
521                         public SyncMethodInvoker (MethodInfo methodInfo) {
522                                 _methodInfo = methodInfo;
523                         }
524                         
525                         #region IOperationInvoker Members
526
527                         public bool IsSynchronous {
528                                 get { return true; }
529                         }
530
531                         public object [] AllocateParameters () {
532                                 return new object [_methodInfo.GetParameters ().Length];
533                         }
534
535                         public object Invoke (object instance, object [] parameters)
536             {
537                                 return _methodInfo.Invoke (instance, parameters);
538                         }
539
540                         public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
541                                 throw new NotSupportedException ();
542                         }
543
544                         public object InvokeEnd (object instance, out object [] outputs, IAsyncResult result) {
545                                 throw new NotSupportedException ();
546                         }
547
548                         #endregion
549                 }
550
551                 class AsyncMethodInvoker : IOperationInvoker
552                 {
553                         readonly MethodInfo _beginMethodInfo, _endMethodInfo;
554                         public AsyncMethodInvoker (MethodInfo beginMethodInfo, MethodInfo endMethodInfo) {
555                                 _beginMethodInfo = beginMethodInfo;
556                                 _endMethodInfo = endMethodInfo;
557                         }
558
559                         #region IOperationInvoker Members
560
561                         public bool IsSynchronous {
562                                 get { return false; }
563                         }
564
565                         public object [] AllocateParameters () {
566                                 return new object [_beginMethodInfo.GetParameters ().Length - 2 + _endMethodInfo.GetParameters().Length-1];
567                         }
568
569                         public object Invoke (object instance, object [] parameters) {
570                                 throw new NotImplementedException ("Can't invoke async method synchronously");
571                                 //BUGBUG: need to differentiate between input and output parameters.
572                                 IAsyncResult asyncResult = InvokeBegin(instance, parameters, delegate(IAsyncResult ignore) { }, null);
573                                 asyncResult.AsyncWaitHandle.WaitOne();
574                                 return InvokeEnd(instance, out parameters, asyncResult);
575                         }
576
577                         public IAsyncResult InvokeBegin (object instance, object [] inputs, AsyncCallback callback, object state) {
578                                 if (inputs.Length + 2 != _beginMethodInfo.GetParameters ().Length)
579                                         throw new ArgumentException ("Wrong number of input parameters");
580                                 object [] fullargs = new object [_beginMethodInfo.GetParameters ().Length];
581                                 Array.Copy (inputs, fullargs, inputs.Length);
582                                 fullargs [inputs.Length] = callback;
583                                 fullargs [inputs.Length + 1] = state;
584                                 return (IAsyncResult) _beginMethodInfo.Invoke (instance, fullargs);
585                         }
586
587                         public object InvokeEnd (object instance, out object [] outputs, IAsyncResult asyncResult) {
588                                 outputs = new object [_endMethodInfo.GetParameters ().Length - 1];
589                                 object [] fullargs = new object [_endMethodInfo.GetParameters ().Length];
590                                 fullargs [outputs.Length] = asyncResult;
591                                 object result = _endMethodInfo.Invoke (instance, fullargs);
592                                 Array.Copy (fullargs, outputs, outputs.Length);
593                                 return result;
594                         }
595
596                         #endregion
597                 }
598                 */
599         }
600
601         partial class DispatcherBuilder
602         {
603                 internal ChannelDispatcher BuildChannelDispatcher (Type serviceType, ServiceEndpoint se, BindingParameterCollection commonParams)
604                 {
605                         //Let all behaviors add their binding parameters
606                         AddBindingParameters (commonParams, se);
607                         //User the binding parameters to build the channel listener and Dispatcher
608                         IChannelListener lf = BuildListener (se, commonParams);
609                         ChannelDispatcher cd = new ChannelDispatcher (
610                                 lf, se.Binding.Name);
611                         cd.InitializeServiceEndpoint (serviceType, se);
612                         return cd;
613                 }
614
615                 private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
616
617                         commonParams.Add (ChannelProtectionRequirements.CreateFromContract (endPoint.Contract));
618
619                         foreach (IContractBehavior b in endPoint.Contract.Behaviors)
620                                 b.AddBindingParameters (endPoint.Contract, endPoint, commonParams);
621                         foreach (IEndpointBehavior b in endPoint.Behaviors)
622                                 b.AddBindingParameters (endPoint, commonParams);
623                         foreach (OperationDescription operation in endPoint.Contract.Operations) {
624                                 foreach (IOperationBehavior b in operation.Behaviors)
625                                         b.AddBindingParameters (operation, commonParams);
626                         }
627                 }
628
629                 static IChannelListener BuildListener (ServiceEndpoint se,
630                         BindingParameterCollection pl)
631                 {
632                         Binding b = se.Binding;
633                         if (b.CanBuildChannelListener<IReplySessionChannel> (pl))
634                                 return b.BuildChannelListener<IReplySessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
635                         if (b.CanBuildChannelListener<IReplyChannel> (pl))
636                                 return b.BuildChannelListener<IReplyChannel> (se.ListenUri, "", se.ListenUriMode, pl);
637                         if (b.CanBuildChannelListener<IInputSessionChannel> (pl))
638                                 return b.BuildChannelListener<IInputSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
639                         if (b.CanBuildChannelListener<IInputChannel> (pl))
640                                 return b.BuildChannelListener<IInputChannel> (se.ListenUri, "", se.ListenUriMode, pl);
641
642                         if (b.CanBuildChannelListener<IDuplexChannel> (pl))
643                                 return b.BuildChannelListener<IDuplexChannel> (se.ListenUri, "", se.ListenUriMode, pl);
644                         if (b.CanBuildChannelListener<IDuplexSessionChannel> (pl))
645                                 return b.BuildChannelListener<IDuplexSessionChannel> (se.ListenUri, "", se.ListenUriMode, pl);
646                         throw new InvalidOperationException ("None of the listener channel types is supported");
647                 }
648         }
649 }