ServiceHost.cs 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Collections.ObjectModel;
  9. using System.ComponentModel;
  10. using System.Diagnostics;
  11. using System.Globalization;
  12. using System.Net;
  13. using System.Runtime;
  14. using System.Security;
  15. using System.ServiceModel.Administration;
  16. using System.ServiceModel.Channels;
  17. using System.ServiceModel.Configuration;
  18. using System.ServiceModel.Description;
  19. using System.ServiceModel.Diagnostics;
  20. using System.ServiceModel.Dispatcher;
  21. using System.Text;
  22. using System.Runtime.Diagnostics;
  23. using System.Threading;
  24. using System.ServiceModel.Activation;
  25. using System.ServiceModel.Diagnostics.Application;
  26. using System.Reflection;
  27. using System.Linq.Expressions;
  28. public abstract class ServiceHostBase : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
  29. {
  30. internal static readonly Uri EmptyUri = new Uri(string.Empty, UriKind.RelativeOrAbsolute);
  31. bool initializeDescriptionHasFinished;
  32. UriSchemeKeyedCollection baseAddresses;
  33. ChannelDispatcherCollection channelDispatchers;
  34. TimeSpan closeTimeout = ServiceDefaults.ServiceHostCloseTimeout;
  35. ServiceDescription description;
  36. ExtensionCollection<ServiceHostBase> extensions;
  37. ReadOnlyCollection<Uri> externalBaseAddresses;
  38. IDictionary<string, ContractDescription> implementedContracts;
  39. IInstanceContextManager instances;
  40. TimeSpan openTimeout = ServiceDefaults.OpenTimeout;
  41. ServicePerformanceCountersBase servicePerformanceCounters;
  42. DefaultPerformanceCounters defaultPerformanceCounters;
  43. ServiceThrottle serviceThrottle;
  44. ServiceCredentials readOnlyCredentials;
  45. ServiceAuthorizationBehavior readOnlyAuthorization;
  46. ServiceAuthenticationBehavior readOnlyAuthentication;
  47. Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> endpointsByListenUriInfo;
  48. int busyCount;
  49. EventTraceActivity eventTraceActivity;
  50. internal event EventHandler BusyCountIncremented;
  51. public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived;
  52. protected ServiceHostBase()
  53. {
  54. TraceUtility.SetEtwProviderId();
  55. this.baseAddresses = new UriSchemeKeyedCollection(this.ThisLock);
  56. this.channelDispatchers = new ChannelDispatcherCollection(this, this.ThisLock);
  57. this.extensions = new ExtensionCollection<ServiceHostBase>(this, this.ThisLock);
  58. this.instances = new InstanceContextManager(this.ThisLock);
  59. this.serviceThrottle = new ServiceThrottle(this);
  60. this.TraceOpenAndClose = true;
  61. this.Faulted += new EventHandler(OnServiceHostFaulted);
  62. }
  63. internal EventTraceActivity EventTraceActivity
  64. {
  65. get
  66. {
  67. if (this.eventTraceActivity == null)
  68. {
  69. this.eventTraceActivity = new EventTraceActivity();
  70. }
  71. return eventTraceActivity;
  72. }
  73. }
  74. public ServiceAuthorizationBehavior Authorization
  75. {
  76. get
  77. {
  78. if (this.Description == null)
  79. {
  80. return null;
  81. }
  82. else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening)
  83. {
  84. return EnsureAuthorization(this.Description);
  85. }
  86. else
  87. {
  88. return this.readOnlyAuthorization;
  89. }
  90. }
  91. }
  92. public ServiceAuthenticationBehavior Authentication
  93. {
  94. get
  95. {
  96. if (this.Description == null)
  97. {
  98. return null;
  99. }
  100. else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening)
  101. {
  102. return EnsureAuthentication(this.Description);
  103. }
  104. else
  105. {
  106. return this.readOnlyAuthentication;
  107. }
  108. }
  109. }
  110. public ReadOnlyCollection<Uri> BaseAddresses
  111. {
  112. get
  113. {
  114. externalBaseAddresses = new ReadOnlyCollection<Uri>(new List<Uri>(this.baseAddresses));
  115. return externalBaseAddresses;
  116. }
  117. }
  118. public ChannelDispatcherCollection ChannelDispatchers
  119. {
  120. get { return this.channelDispatchers; }
  121. }
  122. public TimeSpan CloseTimeout
  123. {
  124. get { return this.closeTimeout; }
  125. set
  126. {
  127. if (value < TimeSpan.Zero)
  128. {
  129. string message = SR.GetString(SR.SFxTimeoutOutOfRange0);
  130. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", message));
  131. }
  132. if (TimeoutHelper.IsTooLarge(value))
  133. {
  134. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
  135. }
  136. lock (this.ThisLock)
  137. {
  138. this.ThrowIfClosedOrOpened();
  139. this.closeTimeout = value;
  140. }
  141. }
  142. }
  143. internal ServicePerformanceCountersBase Counters
  144. {
  145. get
  146. {
  147. return this.servicePerformanceCounters;
  148. }
  149. set
  150. {
  151. this.servicePerformanceCounters = value;
  152. this.serviceThrottle.SetServicePerformanceCounters(this.servicePerformanceCounters);
  153. }
  154. }
  155. internal DefaultPerformanceCounters DefaultCounters
  156. {
  157. get
  158. {
  159. return this.defaultPerformanceCounters;
  160. }
  161. set
  162. {
  163. this.defaultPerformanceCounters = value;
  164. }
  165. }
  166. public ServiceCredentials Credentials
  167. {
  168. get
  169. {
  170. if (this.Description == null)
  171. {
  172. return null;
  173. }
  174. else if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening)
  175. {
  176. return EnsureCredentials(this.Description);
  177. }
  178. else
  179. {
  180. return this.readOnlyCredentials;
  181. }
  182. }
  183. }
  184. protected override TimeSpan DefaultCloseTimeout
  185. {
  186. get { return this.CloseTimeout; }
  187. }
  188. protected override TimeSpan DefaultOpenTimeout
  189. {
  190. get { return this.OpenTimeout; }
  191. }
  192. public ServiceDescription Description
  193. {
  194. get { return this.description; }
  195. }
  196. public IExtensionCollection<ServiceHostBase> Extensions
  197. {
  198. get { return this.extensions; }
  199. }
  200. protected internal IDictionary<string, ContractDescription> ImplementedContracts
  201. {
  202. get { return this.implementedContracts; }
  203. }
  204. internal UriSchemeKeyedCollection InternalBaseAddresses
  205. {
  206. get { return this.baseAddresses; }
  207. }
  208. public int ManualFlowControlLimit
  209. {
  210. get { return this.ServiceThrottle.ManualFlowControlLimit; }
  211. set { this.ServiceThrottle.ManualFlowControlLimit = value; }
  212. }
  213. public TimeSpan OpenTimeout
  214. {
  215. get { return this.openTimeout; }
  216. set
  217. {
  218. if (value < TimeSpan.Zero)
  219. {
  220. string message = SR.GetString(SR.SFxTimeoutOutOfRange0);
  221. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", message));
  222. }
  223. if (TimeoutHelper.IsTooLarge(value))
  224. {
  225. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
  226. }
  227. lock (this.ThisLock)
  228. {
  229. this.ThrowIfClosedOrOpened();
  230. this.openTimeout = value;
  231. }
  232. }
  233. }
  234. internal ServiceThrottle ServiceThrottle
  235. {
  236. get
  237. {
  238. return this.serviceThrottle;
  239. }
  240. }
  241. internal virtual object DisposableInstance
  242. {
  243. get
  244. {
  245. return null;
  246. }
  247. }
  248. internal Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> EndpointsByListenUriInfo
  249. {
  250. get
  251. {
  252. if (this.endpointsByListenUriInfo == null)
  253. {
  254. this.endpointsByListenUriInfo = this.GetEndpointsByListenUriInfo();
  255. }
  256. return this.endpointsByListenUriInfo;
  257. }
  258. }
  259. Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> GetEndpointsByListenUriInfo()
  260. {
  261. Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>> endpointDictionary = new Dictionary<DispatcherBuilder.ListenUriInfo, Collection<ServiceEndpoint>>();
  262. foreach (ServiceEndpoint endpoint in this.Description.Endpoints)
  263. {
  264. DispatcherBuilder.ListenUriInfo listenUriInfo = DispatcherBuilder.GetListenUriInfoForEndpoint(this, endpoint);
  265. if (!endpointDictionary.ContainsKey(listenUriInfo))
  266. {
  267. endpointDictionary.Add(listenUriInfo, new Collection<ServiceEndpoint>());
  268. }
  269. endpointDictionary[listenUriInfo].Add(endpoint);
  270. }
  271. return endpointDictionary;
  272. }
  273. protected void AddBaseAddress(Uri baseAddress)
  274. {
  275. if (this.initializeDescriptionHasFinished)
  276. {
  277. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  278. SR.GetString(SR.SFxCannotCallAddBaseAddress)));
  279. }
  280. this.baseAddresses.Add(baseAddress);
  281. }
  282. public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address)
  283. {
  284. return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null);
  285. }
  286. public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri)
  287. {
  288. if (address == null)
  289. {
  290. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address"));
  291. }
  292. ServiceEndpoint endpoint = this.AddServiceEndpoint(implementedContract, binding, new Uri(address, UriKind.RelativeOrAbsolute));
  293. if (listenUri != null)
  294. {
  295. endpoint.UnresolvedListenUri = listenUri;
  296. listenUri = MakeAbsoluteUri(listenUri, binding);
  297. endpoint.ListenUri = listenUri;
  298. }
  299. return endpoint;
  300. }
  301. public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address)
  302. {
  303. return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null);
  304. }
  305. public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri)
  306. {
  307. if (address == null)
  308. {
  309. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address"));
  310. }
  311. if (binding == null)
  312. {
  313. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("binding"));
  314. }
  315. if (implementedContract == null)
  316. {
  317. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("implementedContract"));
  318. }
  319. if (this.State != CommunicationState.Created && this.State != CommunicationState.Opening)
  320. {
  321. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointAfterOpen)));
  322. }
  323. if (this.Description == null)
  324. {
  325. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointWithoutDescription)));
  326. }
  327. Uri via = this.MakeAbsoluteUri(address, binding);
  328. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.implementedContracts));
  329. ContractDescription contract = configLoader.LookupContract(implementedContract, this.Description.Name);
  330. ServiceEndpoint serviceEndpoint = new ServiceEndpoint(contract, binding, new EndpointAddress(via));
  331. this.Description.Endpoints.Add(serviceEndpoint);
  332. serviceEndpoint.UnresolvedAddress = address;
  333. if (listenUri != null)
  334. {
  335. serviceEndpoint.UnresolvedListenUri = listenUri;
  336. listenUri = MakeAbsoluteUri(listenUri, binding);
  337. serviceEndpoint.ListenUri = listenUri;
  338. }
  339. return serviceEndpoint;
  340. }
  341. public virtual void AddServiceEndpoint(ServiceEndpoint endpoint)
  342. {
  343. if (endpoint == null)
  344. {
  345. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
  346. }
  347. if (this.State != CommunicationState.Created && this.State != CommunicationState.Opening)
  348. {
  349. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointAfterOpen)));
  350. }
  351. if (this.Description == null)
  352. {
  353. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotAddEndpointWithoutDescription)));
  354. }
  355. if (endpoint.Address == null)
  356. {
  357. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointAddressNotSpecified));
  358. }
  359. if (endpoint.Contract == null)
  360. {
  361. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointContractNotSpecified));
  362. }
  363. if (endpoint.Binding == null)
  364. {
  365. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointBindingNotSpecified));
  366. }
  367. if (!endpoint.IsSystemEndpoint || endpoint.Contract.ContractType == typeof(IMetadataExchange))
  368. {
  369. ConfigLoader loader = new ConfigLoader(GetContractResolver(this.implementedContracts));
  370. loader.LookupContract(endpoint.Contract.ConfigurationName, this.Description.Name);
  371. }
  372. this.Description.Endpoints.Add(endpoint);
  373. }
  374. public void SetEndpointAddress(ServiceEndpoint endpoint, string relativeAddress)
  375. {
  376. if (endpoint == null)
  377. {
  378. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
  379. }
  380. if (relativeAddress == null)
  381. {
  382. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("relativeAddress");
  383. }
  384. if (endpoint.Binding == null)
  385. {
  386. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxEndpointBindingNotSpecified));
  387. }
  388. Uri absoluteUri = MakeAbsoluteUri(new Uri(relativeAddress, UriKind.Relative), endpoint.Binding);
  389. endpoint.Address = new EndpointAddress(absoluteUri);
  390. }
  391. internal Uri MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding)
  392. {
  393. return MakeAbsoluteUri(relativeOrAbsoluteUri, binding, this.InternalBaseAddresses);
  394. }
  395. internal static Uri MakeAbsoluteUri(Uri relativeOrAbsoluteUri, Binding binding, UriSchemeKeyedCollection baseAddresses)
  396. {
  397. Uri result = relativeOrAbsoluteUri;
  398. if (!result.IsAbsoluteUri)
  399. {
  400. if (binding.Scheme == string.Empty)
  401. {
  402. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxCustomBindingWithoutTransport)));
  403. }
  404. result = GetVia(binding.Scheme, result, baseAddresses);
  405. if (result == null)
  406. {
  407. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxEndpointNoMatchingScheme, binding.Scheme, binding.Name, GetBaseAddressSchemes(baseAddresses))));
  408. }
  409. }
  410. return result;
  411. }
  412. protected virtual void ApplyConfiguration()
  413. {
  414. if (this.Description == null)
  415. {
  416. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription)));
  417. }
  418. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(implementedContracts));
  419. // Call the overload of LoadConfigurationSectionInternal which looks up the serviceElement from ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  420. LoadConfigurationSectionInternal(configLoader, this.Description, this.Description.ConfigurationName);
  421. EnsureAuthenticationAuthorizationDebug(this.Description);
  422. }
  423. internal void EnsureAuthenticationAuthorizationDebug(ServiceDescription description)
  424. {
  425. EnsureAuthentication(description);
  426. EnsureAuthorization(description);
  427. EnsureDebug(description);
  428. }
  429. public virtual ReadOnlyCollection<ServiceEndpoint> AddDefaultEndpoints()
  430. {
  431. List<ServiceEndpoint> defaultEndpoints = new List<ServiceEndpoint>();
  432. foreach (Uri baseAddress in this.InternalBaseAddresses)
  433. {
  434. ProtocolMappingItem protocolMappingItem = ConfigLoader.LookupProtocolMapping(baseAddress.Scheme);
  435. if (protocolMappingItem != null)
  436. {
  437. Binding defaultBinding = ConfigLoader.LookupBinding(protocolMappingItem.Binding, protocolMappingItem.BindingConfiguration);
  438. if (defaultBinding != null)
  439. {
  440. AddDefaultEndpoints(defaultBinding, defaultEndpoints);
  441. }
  442. else
  443. {
  444. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Exception(SR.GetString(SR.BindingProtocolMappingNotDefined, baseAddress.Scheme)));
  445. }
  446. }
  447. }
  448. if (DiagnosticUtility.ShouldTraceInformation && defaultEndpoints.Count > 0)
  449. {
  450. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  451. dictionary["ServiceConfigurationName"] = this.description.ConfigurationName;
  452. TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DefaultEndpointsAdded, SR.GetString(SR.TraceCodeDefaultEndpointsAdded), new DictionaryTraceRecord(dictionary));
  453. }
  454. return new ReadOnlyCollection<ServiceEndpoint>(defaultEndpoints);
  455. }
  456. internal virtual void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints)
  457. {
  458. }
  459. internal virtual void BindInstance(InstanceContext instance)
  460. {
  461. this.instances.Add(instance);
  462. if (null != this.servicePerformanceCounters)
  463. {
  464. lock (this.ThisLock)
  465. {
  466. if (null != this.servicePerformanceCounters)
  467. {
  468. this.servicePerformanceCounters.ServiceInstanceCreated();
  469. }
  470. }
  471. }
  472. }
  473. void IDisposable.Dispose()
  474. {
  475. Close();
  476. }
  477. protected abstract ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts);
  478. protected virtual void InitializeRuntime()
  479. {
  480. if (this.Description == null)
  481. {
  482. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotInitializeRuntimeWithoutDescription)));
  483. }
  484. if (this.Description.Endpoints.Count == 0)
  485. {
  486. this.AddDefaultEndpoints();
  487. }
  488. this.EnsureAuthenticationSchemes();
  489. DispatcherBuilder dispatcherBuilder = new DispatcherBuilder();
  490. dispatcherBuilder.InitializeServiceHost(description, this);
  491. SecurityValidationBehavior.Instance.AfterBuildTimeValidation(description);
  492. }
  493. internal virtual void AfterInitializeRuntime(TimeSpan timeout)
  494. {
  495. }
  496. internal virtual IAsyncResult BeginAfterInitializeRuntime(TimeSpan timeout, AsyncCallback callback, object state)
  497. {
  498. return new CompletedAsyncResult(callback, state);
  499. }
  500. internal virtual void EndAfterInitializeRuntime(IAsyncResult result)
  501. {
  502. CompletedAsyncResult.End(result);
  503. }
  504. ServiceAuthorizationBehavior EnsureAuthorization(ServiceDescription description)
  505. {
  506. Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
  507. ServiceAuthorizationBehavior a = description.Behaviors.Find<ServiceAuthorizationBehavior>();
  508. if (a == null)
  509. {
  510. a = new ServiceAuthorizationBehavior();
  511. description.Behaviors.Add(a);
  512. }
  513. return a;
  514. }
  515. ServiceAuthenticationBehavior EnsureAuthentication(ServiceDescription description)
  516. {
  517. Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
  518. ServiceAuthenticationBehavior a = description.Behaviors.Find<ServiceAuthenticationBehavior>();
  519. if (a == null)
  520. {
  521. a = new ServiceAuthenticationBehavior();
  522. description.Behaviors.Add(a);
  523. }
  524. return a;
  525. }
  526. ServiceDebugBehavior EnsureDebug(ServiceDescription description)
  527. {
  528. Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
  529. ServiceDebugBehavior m = description.Behaviors.Find<ServiceDebugBehavior>();
  530. if (m == null)
  531. {
  532. m = new ServiceDebugBehavior();
  533. description.Behaviors.Add(m);
  534. }
  535. return m;
  536. }
  537. ServiceCredentials EnsureCredentials(ServiceDescription description)
  538. {
  539. Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, "");
  540. ServiceCredentials c = description.Behaviors.Find<ServiceCredentials>();
  541. if (c == null)
  542. {
  543. c = new ServiceCredentials();
  544. description.Behaviors.Add(c);
  545. }
  546. return c;
  547. }
  548. internal void FaultInternal()
  549. {
  550. this.Fault();
  551. }
  552. internal string GetBaseAddressSchemes()
  553. {
  554. return GetBaseAddressSchemes(baseAddresses);
  555. }
  556. internal static String GetBaseAddressSchemes(UriSchemeKeyedCollection uriSchemeKeyedCollection)
  557. {
  558. StringBuilder buffer = new StringBuilder();
  559. bool firstScheme = true;
  560. foreach (Uri address in uriSchemeKeyedCollection)
  561. {
  562. if (firstScheme)
  563. {
  564. buffer.Append(address.Scheme);
  565. firstScheme = false;
  566. }
  567. else
  568. {
  569. buffer.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator).Append(address.Scheme);
  570. }
  571. }
  572. return buffer.ToString();
  573. }
  574. internal BindingParameterCollection GetBindingParameters()
  575. {
  576. return DispatcherBuilder.GetBindingParameters(this, new Collection<ServiceEndpoint>());
  577. }
  578. internal BindingParameterCollection GetBindingParameters(ServiceEndpoint inputEndpoint)
  579. {
  580. Collection<ServiceEndpoint> endpoints;
  581. if (inputEndpoint == null)
  582. {
  583. endpoints = new Collection<ServiceEndpoint>();
  584. }
  585. else if (!this.EndpointsByListenUriInfo.TryGetValue(DispatcherBuilder.GetListenUriInfoForEndpoint(this, inputEndpoint), out endpoints) || !endpoints.Contains(inputEndpoint))
  586. {
  587. endpoints = new Collection<ServiceEndpoint>();
  588. endpoints.Add(inputEndpoint);
  589. }
  590. return DispatcherBuilder.GetBindingParameters(this, endpoints);
  591. }
  592. internal BindingParameterCollection GetBindingParameters(Collection<ServiceEndpoint> endpoints)
  593. {
  594. return DispatcherBuilder.GetBindingParameters(this, endpoints);
  595. }
  596. internal ReadOnlyCollection<InstanceContext> GetInstanceContexts()
  597. {
  598. return Array.AsReadOnly<InstanceContext>(this.instances.ToArray());
  599. }
  600. internal virtual IContractResolver GetContractResolver(IDictionary<string, ContractDescription> implementedContracts)
  601. {
  602. ServiceAndBehaviorsContractResolver resolver = new ServiceAndBehaviorsContractResolver(new ImplementedContractsContractResolver(implementedContracts));
  603. resolver.AddBehaviorContractsToResolver(this.description == null ? null : this.description.Behaviors);
  604. return resolver;
  605. }
  606. internal static Uri GetUri(Uri baseUri, Uri relativeUri)
  607. {
  608. return GetUri(baseUri, relativeUri.OriginalString);
  609. }
  610. internal static Uri GetUri(Uri baseUri, string path)
  611. {
  612. if (path.StartsWith("/", StringComparison.Ordinal) || path.StartsWith("\\", StringComparison.Ordinal))
  613. {
  614. int i = 1;
  615. for (; i < path.Length; ++i)
  616. {
  617. if (path[i] != '/' && path[i] != '\\')
  618. {
  619. break;
  620. }
  621. }
  622. path = path.Substring(i);
  623. }
  624. // VSWhidbey#541152: new Uri(Uri, string.Empty) is broken
  625. if (path.Length == 0)
  626. return baseUri;
  627. if (!baseUri.AbsoluteUri.EndsWith("/", StringComparison.Ordinal))
  628. {
  629. baseUri = new Uri(baseUri.AbsoluteUri + "/");
  630. }
  631. return new Uri(baseUri, path);
  632. }
  633. internal Uri GetVia(string scheme, Uri address)
  634. {
  635. return ServiceHost.GetVia(scheme, address, InternalBaseAddresses);
  636. }
  637. internal static Uri GetVia(string scheme, Uri address, UriSchemeKeyedCollection baseAddresses)
  638. {
  639. Uri via = address;
  640. if (!via.IsAbsoluteUri)
  641. {
  642. if (!baseAddresses.Contains(scheme))
  643. {
  644. return null;
  645. }
  646. via = GetUri(baseAddresses[scheme], address);
  647. }
  648. return via;
  649. }
  650. public int IncrementManualFlowControlLimit(int incrementBy)
  651. {
  652. return this.ServiceThrottle.IncrementManualFlowControlLimit(incrementBy);
  653. }
  654. protected void InitializeDescription(UriSchemeKeyedCollection baseAddresses)
  655. {
  656. foreach (Uri baseAddress in baseAddresses)
  657. {
  658. this.baseAddresses.Add(baseAddress);
  659. }
  660. IDictionary<string, ContractDescription> implementedContracts = null;
  661. ServiceDescription description = CreateDescription(out implementedContracts);
  662. this.description = description;
  663. this.implementedContracts = implementedContracts;
  664. ApplyConfiguration();
  665. this.initializeDescriptionHasFinished = true;
  666. }
  667. protected void LoadConfigurationSection(ServiceElement serviceSection)
  668. {
  669. if (serviceSection == null)
  670. {
  671. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceSection");
  672. }
  673. if (this.Description == null)
  674. {
  675. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotLoadConfigurationSectionWithoutDescription)));
  676. }
  677. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts));
  678. LoadConfigurationSectionInternal(configLoader, this.Description, serviceSection);
  679. }
  680. internal void LoadConfigurationSectionHelper(Uri baseAddress)
  681. {
  682. this.AddBaseAddress(baseAddress);
  683. }
  684. [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.",
  685. Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")]
  686. [SecuritySafeCritical]
  687. void LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName)
  688. {
  689. ServiceElement serviceSection = configLoader.LookupService(configurationName);
  690. LoadConfigurationSectionInternal(configLoader, description, serviceSection);
  691. }
  692. [Fx.Tag.SecurityNote(Critical = "Handles a ServiceElement, which should not be leaked out of SecurityCritical code.",
  693. Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")]
  694. [SecuritySafeCritical]
  695. void LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection)
  696. {
  697. // caller must validate arguments before calling
  698. configLoader.LoadServiceDescription(this, description, serviceSection, this.LoadConfigurationSectionHelper);
  699. }
  700. protected override void OnAbort()
  701. {
  702. this.instances.Abort();
  703. foreach (ChannelDispatcherBase dispatcher in this.ChannelDispatchers)
  704. {
  705. if (dispatcher.Listener != null)
  706. {
  707. dispatcher.Listener.Abort();
  708. }
  709. dispatcher.Abort();
  710. }
  711. ThreadTrace.StopTracing();
  712. }
  713. internal void OnAddChannelDispatcher(ChannelDispatcherBase channelDispatcher)
  714. {
  715. lock (this.ThisLock)
  716. {
  717. this.ThrowIfClosedOrOpened();
  718. channelDispatcher.AttachInternal(this);
  719. channelDispatcher.Faulted += new EventHandler(OnChannelDispatcherFaulted);
  720. }
  721. }
  722. protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  723. {
  724. return new CloseAsyncResult(timeout, callback, state, this);
  725. }
  726. void OnBeginOpen()
  727. {
  728. this.TraceServiceHostOpenStart();
  729. this.TraceBaseAddresses();
  730. MessageLogger.EnsureInitialized(); //force config validation instead of waiting for the first message exchange
  731. InitializeRuntime();
  732. }
  733. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  734. {
  735. this.OnBeginOpen();
  736. return new OpenAsyncResult(this, timeout, callback, state);
  737. }
  738. IAsyncResult BeginOpenChannelDispatchers(TimeSpan timeout, AsyncCallback callback, object state)
  739. {
  740. return new OpenCollectionAsyncResult(timeout, callback, state, this.SnapshotChannelDispatchers());
  741. }
  742. protected override void OnClose(TimeSpan timeout)
  743. {
  744. try
  745. {
  746. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  747. if (ManagementExtension.IsEnabled && null != this.Description)
  748. {
  749. ManagementExtension.OnServiceClosing(this);
  750. }
  751. for (int i = 0; i < this.ChannelDispatchers.Count; i++)
  752. {
  753. ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i];
  754. if (dispatcher.Listener != null)
  755. {
  756. dispatcher.Listener.Close(timeoutHelper.RemainingTime());
  757. }
  758. }
  759. for (int i = 0; i < this.ChannelDispatchers.Count; i++)
  760. {
  761. ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i];
  762. dispatcher.CloseInput(timeoutHelper.RemainingTime());
  763. }
  764. // Wait for existing work to complete
  765. this.instances.CloseInput(timeoutHelper.RemainingTime());
  766. // Close instances (closes contexts/channels)
  767. this.instances.Close(timeoutHelper.RemainingTime());
  768. // Close dispatchers
  769. for (int i = 0; i < this.ChannelDispatchers.Count; i++)
  770. {
  771. ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i];
  772. dispatcher.Close(timeoutHelper.RemainingTime());
  773. }
  774. this.ReleasePerformanceCounters();
  775. this.TraceBaseAddresses();
  776. ThreadTrace.StopTracing();
  777. }
  778. catch (TimeoutException e)
  779. {
  780. if (TD.CloseTimeoutIsEnabled())
  781. {
  782. TD.CloseTimeout(SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose));
  783. }
  784. if (DiagnosticUtility.ShouldTraceWarning)
  785. {
  786. TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostTimeoutOnClose, SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose), this, e);
  787. }
  788. this.Abort();
  789. }
  790. }
  791. protected override void OnClosed()
  792. {
  793. try
  794. {
  795. for (int i = 0; i < this.ChannelDispatchers.Count; i++)
  796. {
  797. ChannelDispatcher dispatcher = this.ChannelDispatchers[i] as ChannelDispatcher;
  798. if (dispatcher != null)
  799. {
  800. dispatcher.ReleasePerformanceCounters();
  801. }
  802. }
  803. }
  804. finally
  805. {
  806. base.OnClosed();
  807. }
  808. }
  809. void TraceBaseAddresses()
  810. {
  811. if (DiagnosticUtility.ShouldTraceInformation && this.baseAddresses != null
  812. && this.baseAddresses.Count > 0)
  813. {
  814. TraceUtility.TraceEvent(TraceEventType.Information,
  815. TraceCode.ServiceHostBaseAddresses,
  816. SR.GetString(SR.TraceCodeServiceHostBaseAddresses),
  817. new CollectionTraceRecord("BaseAddresses", "Address", this.baseAddresses),
  818. this, null);
  819. }
  820. }
  821. void TraceServiceHostOpenStart()
  822. {
  823. if (TD.ServiceHostOpenStartIsEnabled())
  824. {
  825. TD.ServiceHostOpenStart(this.EventTraceActivity);
  826. }
  827. }
  828. protected override void OnEndClose(IAsyncResult result)
  829. {
  830. try
  831. {
  832. CloseAsyncResult.End(result);
  833. this.TraceBaseAddresses();
  834. ThreadTrace.StopTracing();
  835. }
  836. catch (TimeoutException e)
  837. {
  838. if (TD.CloseTimeoutIsEnabled())
  839. {
  840. TD.CloseTimeout(SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose));
  841. }
  842. if (DiagnosticUtility.ShouldTraceWarning)
  843. {
  844. TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostTimeoutOnClose,
  845. SR.GetString(SR.TraceCodeServiceHostTimeoutOnClose), this, e);
  846. }
  847. this.Abort();
  848. }
  849. }
  850. protected override void OnEndOpen(IAsyncResult result)
  851. {
  852. OpenAsyncResult.End(result);
  853. }
  854. void EndOpenChannelDispatchers(IAsyncResult result)
  855. {
  856. OpenCollectionAsyncResult.End(result);
  857. }
  858. void EnsureAuthenticationSchemes()
  859. {
  860. if (this.Authentication == null)
  861. {
  862. return;
  863. }
  864. //Exit immediately when not hosted in IIS or if VirtualPathExtension is not set. VirtualPathExtension is used as a flag to indicate whether a ServiceHost
  865. // is webhosted (WsDualHttpBinding-ChannelFactory is using HttpListener instead of IIS even when running in IIS)
  866. if (!AspNetEnvironment.Enabled ||
  867. this.Extensions.Find<VirtualPathExtension>() == null)
  868. {
  869. return;
  870. }
  871. foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints)
  872. {
  873. if (serviceEndpoint.Binding != null &&
  874. serviceEndpoint.ListenUri != null &&
  875. ("http".Equals(serviceEndpoint.ListenUri.Scheme, StringComparison.OrdinalIgnoreCase) || "https".Equals(serviceEndpoint.ListenUri.Scheme, StringComparison.OrdinalIgnoreCase)) &&
  876. this.baseAddresses.Contains(serviceEndpoint.ListenUri.Scheme))
  877. {
  878. HttpTransportBindingElement httpTransportBindingElement = serviceEndpoint.Binding.CreateBindingElements().Find<HttpTransportBindingElement>();
  879. if (httpTransportBindingElement != null)
  880. {
  881. AuthenticationSchemes hostSupportedAuthenticationSchemes = AspNetEnvironment.Current.GetAuthenticationSchemes(this.baseAddresses[serviceEndpoint.ListenUri.Scheme]);
  882. if (hostSupportedAuthenticationSchemes != AuthenticationSchemes.None)
  883. {
  884. //If no authentication schemes are explicitly defined for the ServiceHost...
  885. if (this.Authentication.AuthenticationSchemes == AuthenticationSchemes.None)
  886. {
  887. //Inherit authentication schemes from IIS
  888. this.Authentication.AuthenticationSchemes = hostSupportedAuthenticationSchemes;
  889. }
  890. else
  891. {
  892. // Build intersection between authenticationSchemes on the ServiceHost and in IIS
  893. this.Authentication.AuthenticationSchemes &= hostSupportedAuthenticationSchemes;
  894. }
  895. }
  896. }
  897. break;
  898. }
  899. }
  900. }
  901. protected override void OnOpen(TimeSpan timeout)
  902. {
  903. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  904. this.OnBeginOpen();
  905. AfterInitializeRuntime(timeoutHelper.RemainingTime());
  906. for (int i = 0; i < this.ChannelDispatchers.Count; i++)
  907. {
  908. ChannelDispatcherBase dispatcher = this.ChannelDispatchers[i];
  909. dispatcher.Open(timeoutHelper.RemainingTime());
  910. }
  911. }
  912. protected override void OnOpened()
  913. {
  914. if (this.Description != null)
  915. {
  916. ServiceCredentials c = description.Behaviors.Find<ServiceCredentials>();
  917. if (c != null)
  918. {
  919. ServiceCredentials credentialsCopy = c.Clone();
  920. credentialsCopy.MakeReadOnly();
  921. this.readOnlyCredentials = credentialsCopy;
  922. }
  923. ServiceAuthorizationBehavior authorization = description.Behaviors.Find<ServiceAuthorizationBehavior>();
  924. if (authorization != null)
  925. {
  926. ServiceAuthorizationBehavior authorizationCopy = authorization.Clone();
  927. authorizationCopy.MakeReadOnly();
  928. this.readOnlyAuthorization = authorizationCopy;
  929. }
  930. ServiceAuthenticationBehavior authentication = description.Behaviors.Find<ServiceAuthenticationBehavior>();
  931. if (authentication != null)
  932. {
  933. ServiceAuthenticationBehavior authenticationCopy = authentication.Clone();
  934. authentication.MakeReadOnly();
  935. this.readOnlyAuthentication = authenticationCopy;
  936. }
  937. if (ManagementExtension.IsEnabled)
  938. {
  939. ManagementExtension.OnServiceOpened(this);
  940. }
  941. }
  942. base.OnOpened();
  943. if (TD.ServiceHostOpenStopIsEnabled())
  944. {
  945. TD.ServiceHostOpenStop(this.EventTraceActivity);
  946. }
  947. }
  948. internal void OnRemoveChannelDispatcher(ChannelDispatcherBase channelDispatcher)
  949. {
  950. lock (this.ThisLock)
  951. {
  952. this.ThrowIfClosedOrOpened();
  953. channelDispatcher.DetachInternal(this);
  954. }
  955. }
  956. void OnChannelDispatcherFaulted(object sender, EventArgs e)
  957. {
  958. this.Fault();
  959. }
  960. void OnServiceHostFaulted(object sender, EventArgs args)
  961. {
  962. if (TD.ServiceHostFaultedIsEnabled())
  963. {
  964. TD.ServiceHostFaulted(this.EventTraceActivity, this);
  965. }
  966. if (DiagnosticUtility.ShouldTraceWarning)
  967. {
  968. TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.ServiceHostFaulted,
  969. SR.GetString(SR.TraceCodeServiceHostFaulted), this);
  970. }
  971. foreach (ICommunicationObject channelDispatcher in this.SnapshotChannelDispatchers())
  972. {
  973. if (channelDispatcher.State == CommunicationState.Opened)
  974. {
  975. channelDispatcher.Abort();
  976. }
  977. }
  978. }
  979. internal void RaiseUnknownMessageReceived(Message message)
  980. {
  981. try
  982. {
  983. EventHandler<UnknownMessageReceivedEventArgs> handler = UnknownMessageReceived;
  984. if (handler != null)
  985. {
  986. handler(this, new UnknownMessageReceivedEventArgs(message));
  987. }
  988. }
  989. catch (Exception e)
  990. {
  991. if (Fx.IsFatal(e))
  992. throw;
  993. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  994. }
  995. }
  996. protected void ReleasePerformanceCounters()
  997. {
  998. if (this.servicePerformanceCounters != null)
  999. {
  1000. lock (this.ThisLock)
  1001. {
  1002. if (this.servicePerformanceCounters != null)
  1003. {
  1004. this.servicePerformanceCounters.Dispose();
  1005. this.servicePerformanceCounters = null;
  1006. }
  1007. }
  1008. }
  1009. if (this.defaultPerformanceCounters != null)
  1010. {
  1011. lock (this.ThisLock)
  1012. {
  1013. if (this.defaultPerformanceCounters != null)
  1014. {
  1015. this.defaultPerformanceCounters.Dispose();
  1016. this.defaultPerformanceCounters = null;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. ICommunicationObject[] SnapshotChannelDispatchers()
  1022. {
  1023. lock (this.ThisLock)
  1024. {
  1025. ICommunicationObject[] array = new ICommunicationObject[this.ChannelDispatchers.Count];
  1026. for (int i = 0; i < array.Length; i++)
  1027. {
  1028. array[i] = this.ChannelDispatchers[i];
  1029. }
  1030. return array;
  1031. }
  1032. }
  1033. internal virtual void UnbindInstance(InstanceContext instance)
  1034. {
  1035. this.instances.Remove(instance);
  1036. if (null != this.servicePerformanceCounters)
  1037. {
  1038. lock (this.ThisLock)
  1039. {
  1040. if (null != this.servicePerformanceCounters)
  1041. {
  1042. this.servicePerformanceCounters.ServiceInstanceRemoved();
  1043. }
  1044. }
  1045. }
  1046. }
  1047. internal void IncrementBusyCount()
  1048. {
  1049. if (AspNetEnvironment.Enabled)
  1050. {
  1051. AspNetEnvironment.Current.IncrementBusyCount();
  1052. Interlocked.Increment(ref this.busyCount);
  1053. }
  1054. EventHandler handler = this.BusyCountIncremented;
  1055. if (handler != null)
  1056. {
  1057. try
  1058. {
  1059. handler(this, EventArgs.Empty);
  1060. }
  1061. catch (Exception exception)
  1062. {
  1063. if (Fx.IsFatal(exception))
  1064. throw;
  1065. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception);
  1066. }
  1067. }
  1068. }
  1069. internal void DecrementBusyCount()
  1070. {
  1071. if (AspNetEnvironment.Enabled)
  1072. {
  1073. Interlocked.Decrement(ref this.busyCount);
  1074. AspNetEnvironment.Current.DecrementBusyCount();
  1075. }
  1076. }
  1077. internal int BusyCount
  1078. {
  1079. get
  1080. {
  1081. return this.busyCount;
  1082. }
  1083. }
  1084. class OpenAsyncResult : AsyncResult
  1085. {
  1086. static AsyncCompletion handleEndAfterInitializeRuntime = new AsyncCompletion(HandleEndAfterInitializeRuntime);
  1087. static AsyncCompletion handleEndOpenChannelDispatchers = new AsyncCompletion(HandleEndOpenChannelDispatchers);
  1088. TimeoutHelper timeoutHelper;
  1089. ServiceHostBase host;
  1090. public OpenAsyncResult(ServiceHostBase host, TimeSpan timeout, AsyncCallback callback, object state)
  1091. : base(callback, state)
  1092. {
  1093. this.timeoutHelper = new TimeoutHelper(timeout);
  1094. this.host = host;
  1095. if (ProcessAfterInitializeRuntime())
  1096. {
  1097. Complete(true);
  1098. }
  1099. }
  1100. bool ProcessAfterInitializeRuntime()
  1101. {
  1102. IAsyncResult result = this.host.BeginAfterInitializeRuntime(
  1103. this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleEndAfterInitializeRuntime), this);
  1104. return SyncContinue(result);
  1105. }
  1106. static bool HandleEndAfterInitializeRuntime(IAsyncResult result)
  1107. {
  1108. OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState;
  1109. thisPtr.host.EndAfterInitializeRuntime(result);
  1110. return thisPtr.ProcessOpenChannelDispatchers();
  1111. }
  1112. bool ProcessOpenChannelDispatchers()
  1113. {
  1114. IAsyncResult result = this.host.BeginOpenChannelDispatchers(
  1115. this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleEndOpenChannelDispatchers), this);
  1116. return SyncContinue(result);
  1117. }
  1118. static bool HandleEndOpenChannelDispatchers(IAsyncResult result)
  1119. {
  1120. OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState;
  1121. thisPtr.host.EndOpenChannelDispatchers(result);
  1122. return true;
  1123. }
  1124. public static void End(IAsyncResult result)
  1125. {
  1126. AsyncResult.End<OpenAsyncResult>(result);
  1127. }
  1128. }
  1129. class CloseAsyncResult : AsyncResult
  1130. {
  1131. ServiceHostBase serviceHost;
  1132. TimeoutHelper timeoutHelper;
  1133. public CloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, ServiceHostBase serviceHost)
  1134. : base(callback, state)
  1135. {
  1136. this.timeoutHelper = new TimeoutHelper(timeout);
  1137. this.serviceHost = serviceHost;
  1138. if (ManagementExtension.IsEnabled && null != serviceHost.Description)
  1139. {
  1140. ManagementExtension.OnServiceClosing(serviceHost);
  1141. }
  1142. this.CloseListeners(true);
  1143. }
  1144. void CloseListeners(bool completedSynchronously)
  1145. {
  1146. List<ICommunicationObject> listeners = new List<ICommunicationObject>();
  1147. for (int i = 0; i < this.serviceHost.ChannelDispatchers.Count; i++)
  1148. {
  1149. if (this.serviceHost.ChannelDispatchers[i].Listener != null)
  1150. {
  1151. listeners.Add(this.serviceHost.ChannelDispatchers[i].Listener);
  1152. }
  1153. }
  1154. AsyncCallback callback = Fx.ThunkCallback(this.CloseListenersCallback);
  1155. TimeSpan timeout = this.timeoutHelper.RemainingTime();
  1156. Exception exception = null;
  1157. IAsyncResult result = null;
  1158. try
  1159. {
  1160. result = new CloseCollectionAsyncResult(timeout, callback, this, listeners);
  1161. }
  1162. catch (Exception e)
  1163. {
  1164. if (Fx.IsFatal(e) || completedSynchronously)
  1165. {
  1166. throw;
  1167. }
  1168. exception = e;
  1169. }
  1170. if (exception != null)
  1171. {
  1172. this.CallComplete(completedSynchronously, exception);
  1173. }
  1174. else if (result.CompletedSynchronously)
  1175. {
  1176. this.FinishCloseListeners(result, completedSynchronously);
  1177. }
  1178. }
  1179. void CloseListenersCallback(IAsyncResult result)
  1180. {
  1181. if (!result.CompletedSynchronously)
  1182. {
  1183. ((CloseAsyncResult)result.AsyncState).FinishCloseListeners(result, false);
  1184. }
  1185. }
  1186. void FinishCloseListeners(IAsyncResult result, bool completedSynchronously)
  1187. {
  1188. Exception exception = null;
  1189. try
  1190. {
  1191. CloseCollectionAsyncResult.End(result);
  1192. }
  1193. catch (Exception e)
  1194. {
  1195. if (Fx.IsFatal(e) || completedSynchronously)
  1196. {
  1197. throw;
  1198. }
  1199. exception = e;
  1200. }
  1201. if (exception != null)
  1202. {
  1203. this.CallComplete(completedSynchronously, exception);
  1204. }
  1205. else
  1206. {
  1207. this.CloseInput(completedSynchronously);
  1208. }
  1209. }
  1210. // Wait for existing work to complete
  1211. void CloseInput(bool completedSynchronously)
  1212. {
  1213. AsyncCallback callback = Fx.ThunkCallback(this.CloseInputCallback);
  1214. Exception exception = null;
  1215. IAsyncResult result = null;
  1216. try
  1217. {
  1218. for (int i = 0; i < this.serviceHost.ChannelDispatchers.Count; i++)
  1219. {
  1220. ChannelDispatcherBase dispatcher = this.serviceHost.ChannelDispatchers[i];
  1221. dispatcher.CloseInput(this.timeoutHelper.RemainingTime());
  1222. }
  1223. result = this.serviceHost.instances.BeginCloseInput(this.timeoutHelper.RemainingTime(), callback, this);
  1224. }
  1225. catch (Exception e)
  1226. {
  1227. if (Fx.IsFatal(e) || completedSynchronously)
  1228. {
  1229. throw;
  1230. }
  1231. exception = e;
  1232. }
  1233. if (exception != null)
  1234. {
  1235. // Any exception during async processing causes this
  1236. // async callback to report the error and then relies on
  1237. // Abort to cleanup any unclosed channels or instance contexts.
  1238. FxTrace.Exception.AsWarning(exception);
  1239. this.CallComplete(completedSynchronously, exception);
  1240. }
  1241. else if (result.CompletedSynchronously)
  1242. {
  1243. this.FinishCloseInput(result, completedSynchronously);
  1244. }
  1245. }
  1246. void CloseInputCallback(IAsyncResult result)
  1247. {
  1248. if (!result.CompletedSynchronously)
  1249. {
  1250. ((CloseAsyncResult)result.AsyncState).FinishCloseInput(result, false);
  1251. }
  1252. }
  1253. void FinishCloseInput(IAsyncResult result, bool completedSynchronously)
  1254. {
  1255. Exception exception = null;
  1256. try
  1257. {
  1258. serviceHost.instances.EndCloseInput(result);
  1259. }
  1260. catch (Exception e)
  1261. {
  1262. if (Fx.IsFatal(e) || completedSynchronously)
  1263. {
  1264. throw;
  1265. }
  1266. exception = e;
  1267. }
  1268. if (exception != null)
  1269. {
  1270. this.CallComplete(completedSynchronously, exception);
  1271. }
  1272. else
  1273. {
  1274. this.CloseInstances(completedSynchronously);
  1275. }
  1276. }
  1277. // Close instances (closes contexts/channels)
  1278. void CloseInstances(bool completedSynchronously)
  1279. {
  1280. AsyncCallback callback = Fx.ThunkCallback(this.CloseInstancesCallback);
  1281. TimeSpan timeout = this.timeoutHelper.RemainingTime();
  1282. Exception exception = null;
  1283. IAsyncResult result = null;
  1284. try
  1285. {
  1286. result = this.serviceHost.instances.BeginClose(timeout, callback, this);
  1287. }
  1288. catch (Exception e)
  1289. {
  1290. if (Fx.IsFatal(e) || completedSynchronously)
  1291. {
  1292. throw;
  1293. }
  1294. exception = e;
  1295. }
  1296. if (exception != null)
  1297. {
  1298. this.CallComplete(completedSynchronously, exception);
  1299. }
  1300. else if (result.CompletedSynchronously)
  1301. {
  1302. this.FinishCloseInstances(result, completedSynchronously);
  1303. }
  1304. }
  1305. void CloseInstancesCallback(IAsyncResult result)
  1306. {
  1307. if (!result.CompletedSynchronously)
  1308. {
  1309. ((CloseAsyncResult)result.AsyncState).FinishCloseInstances(result, false);
  1310. }
  1311. }
  1312. void FinishCloseInstances(IAsyncResult result, bool completedSynchronously)
  1313. {
  1314. Exception exception = null;
  1315. try
  1316. {
  1317. this.serviceHost.instances.EndClose(result);
  1318. }
  1319. catch (Exception e)
  1320. {
  1321. if (Fx.IsFatal(e) || completedSynchronously)
  1322. {
  1323. throw;
  1324. }
  1325. exception = e;
  1326. }
  1327. if (exception != null)
  1328. {
  1329. this.CallComplete(completedSynchronously, exception);
  1330. }
  1331. else
  1332. {
  1333. this.CloseChannelDispatchers(completedSynchronously);
  1334. }
  1335. }
  1336. void CloseChannelDispatchers(bool completedSynchronously)
  1337. {
  1338. IList<ICommunicationObject> channelDispatchers = this.serviceHost.SnapshotChannelDispatchers();
  1339. AsyncCallback callback = Fx.ThunkCallback(this.CloseChannelDispatchersCallback);
  1340. TimeSpan timeout = this.timeoutHelper.RemainingTime();
  1341. Exception exception = null;
  1342. IAsyncResult result = null;
  1343. try
  1344. {
  1345. result = new CloseCollectionAsyncResult(timeout, callback, this, channelDispatchers);
  1346. }
  1347. catch (Exception e)
  1348. {
  1349. if (Fx.IsFatal(e) || completedSynchronously)
  1350. {
  1351. throw;
  1352. }
  1353. exception = e;
  1354. }
  1355. if (exception != null)
  1356. {
  1357. this.CallComplete(completedSynchronously, exception);
  1358. }
  1359. else if (result.CompletedSynchronously)
  1360. {
  1361. this.FinishCloseChannelDispatchers(result, completedSynchronously);
  1362. }
  1363. }
  1364. void CloseChannelDispatchersCallback(IAsyncResult result)
  1365. {
  1366. if (!result.CompletedSynchronously)
  1367. {
  1368. ((CloseAsyncResult)result.AsyncState).FinishCloseChannelDispatchers(result, false);
  1369. }
  1370. }
  1371. void FinishCloseChannelDispatchers(IAsyncResult result, bool completedSynchronously)
  1372. {
  1373. Exception exception = null;
  1374. try
  1375. {
  1376. CloseCollectionAsyncResult.End(result);
  1377. }
  1378. catch (Exception e)
  1379. {
  1380. if (Fx.IsFatal(e) || completedSynchronously)
  1381. {
  1382. throw;
  1383. }
  1384. exception = e;
  1385. }
  1386. this.CallComplete(completedSynchronously, exception);
  1387. }
  1388. void CallComplete(bool completedSynchronously, Exception exception)
  1389. {
  1390. this.Complete(completedSynchronously, exception);
  1391. }
  1392. public static void End(IAsyncResult result)
  1393. {
  1394. AsyncResult.End<CloseAsyncResult>(result);
  1395. }
  1396. }
  1397. class ImplementedContractsContractResolver : IContractResolver
  1398. {
  1399. IDictionary<string, ContractDescription> implementedContracts;
  1400. public ImplementedContractsContractResolver(IDictionary<string, ContractDescription> implementedContracts)
  1401. {
  1402. this.implementedContracts = implementedContracts;
  1403. }
  1404. public ContractDescription ResolveContract(string contractName)
  1405. {
  1406. return this.implementedContracts != null && this.implementedContracts.ContainsKey(contractName) ? this.implementedContracts[contractName] : null;
  1407. }
  1408. }
  1409. internal class ServiceAndBehaviorsContractResolver : IContractResolver
  1410. {
  1411. IContractResolver serviceResolver;
  1412. Dictionary<string, ContractDescription> behaviorContracts;
  1413. public Dictionary<string, ContractDescription> BehaviorContracts
  1414. {
  1415. get { return behaviorContracts; }
  1416. }
  1417. public ServiceAndBehaviorsContractResolver(IContractResolver serviceResolver)
  1418. {
  1419. this.serviceResolver = serviceResolver;
  1420. behaviorContracts = new Dictionary<string, ContractDescription>();
  1421. }
  1422. public ContractDescription ResolveContract(string contractName)
  1423. {
  1424. ContractDescription contract = serviceResolver.ResolveContract(contractName);
  1425. if (contract == null)
  1426. {
  1427. contract = this.behaviorContracts.ContainsKey(contractName) ? this.behaviorContracts[contractName] : null;
  1428. }
  1429. return contract;
  1430. }
  1431. public void AddBehaviorContractsToResolver(KeyedByTypeCollection<IServiceBehavior> behaviors)
  1432. {
  1433. // It would be nice to make this loop over all Behaviors... someday.
  1434. if (behaviors != null && behaviors.Contains(typeof(ServiceMetadataBehavior)))
  1435. {
  1436. behaviors.Find<ServiceMetadataBehavior>().AddImplementedContracts(this);
  1437. }
  1438. }
  1439. }
  1440. }
  1441. public class ServiceHost : ServiceHostBase
  1442. {
  1443. object singletonInstance;
  1444. Type serviceType;
  1445. ReflectedContractCollection reflectedContracts;
  1446. IDisposable disposableInstance;
  1447. protected ServiceHost()
  1448. {
  1449. }
  1450. public ServiceHost(Type serviceType, params Uri[] baseAddresses)
  1451. {
  1452. if (serviceType == null)
  1453. {
  1454. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceType"));
  1455. }
  1456. this.serviceType = serviceType;
  1457. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
  1458. {
  1459. if (DiagnosticUtility.ShouldUseActivity)
  1460. {
  1461. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityConstructServiceHost, serviceType.FullName), ActivityType.Construct);
  1462. }
  1463. InitializeDescription(serviceType, new UriSchemeKeyedCollection(baseAddresses));
  1464. }
  1465. }
  1466. public ServiceHost(object singletonInstance, params Uri[] baseAddresses)
  1467. {
  1468. if (singletonInstance == null)
  1469. {
  1470. throw new ArgumentNullException("singletonInstance");
  1471. }
  1472. this.singletonInstance = singletonInstance;
  1473. this.serviceType = singletonInstance.GetType();
  1474. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
  1475. {
  1476. if (DiagnosticUtility.ShouldUseActivity)
  1477. {
  1478. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityConstructServiceHost, serviceType.FullName), ActivityType.Construct);
  1479. }
  1480. InitializeDescription(singletonInstance, new UriSchemeKeyedCollection(baseAddresses));
  1481. }
  1482. }
  1483. public object SingletonInstance
  1484. {
  1485. get
  1486. {
  1487. return this.singletonInstance;
  1488. }
  1489. }
  1490. internal override object DisposableInstance
  1491. {
  1492. get
  1493. {
  1494. return this.disposableInstance;
  1495. }
  1496. }
  1497. public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, string address)
  1498. {
  1499. return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null);
  1500. }
  1501. public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, string address, Uri listenUri)
  1502. {
  1503. if (address == null)
  1504. {
  1505. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("address"));
  1506. }
  1507. ServiceEndpoint endpoint = this.AddServiceEndpoint(implementedContract, binding, new Uri(address, UriKind.RelativeOrAbsolute));
  1508. if (listenUri != null)
  1509. {
  1510. listenUri = MakeAbsoluteUri(listenUri, binding);
  1511. endpoint.ListenUri = listenUri;
  1512. }
  1513. return endpoint;
  1514. }
  1515. public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, Uri address)
  1516. {
  1517. return this.AddServiceEndpoint(implementedContract, binding, address, (Uri)null);
  1518. }
  1519. void ValidateContractType(Type implementedContract, ReflectedAndBehaviorContractCollection reflectedAndBehaviorContracts)
  1520. {
  1521. if (!implementedContract.IsDefined(typeof(ServiceContractAttribute), false))
  1522. {
  1523. #pragma warning suppress 56506 // implementedContract is never null at this point
  1524. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxServiceContractAttributeNotFound, implementedContract.FullName)));
  1525. }
  1526. if (!reflectedAndBehaviorContracts.Contains(implementedContract))
  1527. {
  1528. if (implementedContract == typeof(IMetadataExchange))
  1529. #pragma warning suppress 56506 // ServiceType is never null at this point
  1530. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFoundIMetadataExchange, this.serviceType.FullName)));
  1531. else
  1532. #pragma warning suppress 56506 // implementedContract and ServiceType are never null at this point
  1533. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFound2, implementedContract.FullName, this.serviceType.FullName)));
  1534. }
  1535. }
  1536. public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, Uri address, Uri listenUri)
  1537. {
  1538. if (implementedContract == null)
  1539. {
  1540. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("implementedContract"));
  1541. }
  1542. if (this.reflectedContracts == null)
  1543. {
  1544. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractsNotInitialized1, implementedContract.FullName)));
  1545. }
  1546. ReflectedAndBehaviorContractCollection reflectedAndBehaviorContracts = new ReflectedAndBehaviorContractCollection(this.reflectedContracts, this.Description.Behaviors);
  1547. ValidateContractType(implementedContract, reflectedAndBehaviorContracts);
  1548. ServiceEndpoint endpoint = AddServiceEndpoint(reflectedAndBehaviorContracts.GetConfigKey(implementedContract), binding, address);
  1549. if (listenUri != null)
  1550. {
  1551. listenUri = MakeAbsoluteUri(listenUri, binding);
  1552. endpoint.ListenUri = listenUri;
  1553. }
  1554. return endpoint;
  1555. }
  1556. internal override void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints)
  1557. {
  1558. // don't generate endpoints for contracts that serve as the base type for other reflected contracts
  1559. List<ContractDescription> mostSpecificContracts = new List<ContractDescription>();
  1560. for (int i = 0; i < this.reflectedContracts.Count; i++)
  1561. {
  1562. bool addContractEndpoint = true;
  1563. ContractDescription contract = this.reflectedContracts[i];
  1564. Type contractType = contract.ContractType;
  1565. if (contractType != null)
  1566. {
  1567. for (int j = 0; j < this.reflectedContracts.Count; j++)
  1568. {
  1569. ContractDescription otherContract = this.reflectedContracts[j];
  1570. Type otherContractType = otherContract.ContractType;
  1571. if (i == j || otherContractType == null)
  1572. {
  1573. continue;
  1574. }
  1575. if (contractType.IsAssignableFrom(otherContractType))
  1576. {
  1577. addContractEndpoint = false;
  1578. break;
  1579. }
  1580. }
  1581. }
  1582. if (addContractEndpoint)
  1583. {
  1584. mostSpecificContracts.Add(contract);
  1585. }
  1586. }
  1587. foreach (ContractDescription contract in mostSpecificContracts)
  1588. {
  1589. ServiceEndpoint endpoint = AddServiceEndpoint(contract.ConfigurationName, defaultBinding, string.Empty);
  1590. ConfigLoader.LoadDefaultEndpointBehaviors(endpoint);
  1591. defaultEndpoints.Add(endpoint);
  1592. }
  1593. }
  1594. // Run static Configure method on service type if it exists, else load configuration from Web.config/App.config
  1595. protected override void ApplyConfiguration()
  1596. {
  1597. // Load from static Configure method if it exists with the right signature
  1598. Type serviceType = this.Description.ServiceType;
  1599. if (serviceType != null)
  1600. {
  1601. MethodInfo configure = GetConfigureMethod(serviceType);
  1602. if (configure != null)
  1603. {
  1604. // load <host> config
  1605. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts));
  1606. LoadHostConfigurationInternal(configLoader, this.Description, this.Description.ConfigurationName);
  1607. // Invoke configure method for service
  1608. ServiceConfiguration configuration = new ServiceConfiguration(this);
  1609. InvokeConfigure(configure, configuration);
  1610. return;
  1611. }
  1612. }
  1613. // else just load from Web.config/App.config
  1614. base.ApplyConfiguration();
  1615. }
  1616. // Find the Configure method with the required signature, closest to serviceType in the type hierarchy
  1617. static MethodInfo GetConfigureMethod(Type serviceType)
  1618. {
  1619. // Use recursion instead of BindingFlags.FlattenHierarchy because we require return type to be void
  1620. // base case: all Types are rooted in object eventually
  1621. if (serviceType == typeof(object))
  1622. {
  1623. return null;
  1624. }
  1625. // signature: "public static void Configure(ServiceConfiguration)"
  1626. MethodInfo configure = serviceType.GetMethod("Configure", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(ServiceConfiguration) }, null);
  1627. if (configure != null && configure.ReturnType == typeof(void))
  1628. {
  1629. return configure;
  1630. }
  1631. else
  1632. {
  1633. return GetConfigureMethod(serviceType.BaseType);
  1634. }
  1635. }
  1636. static void InvokeConfigure(MethodInfo configureMethod, ServiceConfiguration configuration)
  1637. {
  1638. Action<ServiceConfiguration> call = Delegate.CreateDelegate(typeof(Action<ServiceConfiguration>), configureMethod) as Action<ServiceConfiguration>;
  1639. call(configuration);
  1640. }
  1641. // called from ServiceConfiguration.LoadFromConfiguration()
  1642. internal void LoadFromConfiguration()
  1643. {
  1644. if (this.Description == null)
  1645. {
  1646. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription)));
  1647. }
  1648. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts));
  1649. // Call the overload of LoadConfigurationSectionInternal which looks up the serviceElement from ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
  1650. LoadConfigurationSectionExceptHostInternal(configLoader, this.Description, this.Description.ConfigurationName);
  1651. EnsureAuthenticationAuthorizationDebug(this.Description);
  1652. }
  1653. // called from ServiceConfiguration.LoadFromConfiguration(configuration)
  1654. internal void LoadFromConfiguration(System.Configuration.Configuration configuration)
  1655. {
  1656. if (this.Description == null)
  1657. {
  1658. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostBaseCannotApplyConfigurationWithoutDescription)));
  1659. }
  1660. ConfigLoader configLoader = new ConfigLoader(GetContractResolver(this.ImplementedContracts));
  1661. // Look up the serviceElement explicitly on configuration, then call the overload of LoadConfigurationSectionInternal that loads the rest of the config from the same configuration as serviceElement
  1662. ServicesSection servicesSection = (ServicesSection)configuration.GetSection(ConfigurationStrings.ServicesSectionPath);
  1663. ServiceElement serviceElement = configLoader.LookupService(this.Description.ConfigurationName, servicesSection);
  1664. configLoader.LoadServiceDescription(this, this.Description, serviceElement, this.LoadConfigurationSectionHelper, skipHost: true);
  1665. EnsureAuthenticationAuthorizationDebug(this.Description);
  1666. }
  1667. // Load only "host" section within "service" tag
  1668. [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.",
  1669. Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")]
  1670. [SecuritySafeCritical]
  1671. void LoadHostConfigurationInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName)
  1672. {
  1673. ServiceElement serviceSection = configLoader.LookupService(configurationName);
  1674. if (serviceSection != null)
  1675. {
  1676. configLoader.LoadHostConfig(serviceSection, this, (addr => this.InternalBaseAddresses.Add(addr)));
  1677. }
  1678. }
  1679. // Load service description for service from config, but skip "host" section within "service" tag
  1680. [Fx.Tag.SecurityNote(Critical = "Calls LookupService which is critical.",
  1681. Safe = "Doesn't leak ServiceElement out of SecurityCritical code.")]
  1682. [SecuritySafeCritical]
  1683. void LoadConfigurationSectionExceptHostInternal(ConfigLoader configLoader, ServiceDescription description, string configurationName)
  1684. {
  1685. ServiceElement serviceSection = configLoader.LookupService(configurationName);
  1686. configLoader.LoadServiceDescription(this, description, serviceSection, this.LoadConfigurationSectionHelper, skipHost: true);
  1687. }
  1688. internal override string CloseActivityName
  1689. {
  1690. get { return SR.GetString(SR.ActivityCloseServiceHost, this.serviceType.FullName); }
  1691. }
  1692. internal override string OpenActivityName
  1693. {
  1694. get { return SR.GetString(SR.ActivityOpenServiceHost, this.serviceType.FullName); }
  1695. }
  1696. protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
  1697. {
  1698. if (this.serviceType == null)
  1699. {
  1700. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceHostCannotCreateDescriptionWithoutServiceType)));
  1701. }
  1702. ServiceDescription description;
  1703. if (this.SingletonInstance != null)
  1704. {
  1705. description = ServiceDescription.GetService(this.SingletonInstance);
  1706. }
  1707. else
  1708. {
  1709. description = ServiceDescription.GetService(this.serviceType);
  1710. }
  1711. ServiceBehaviorAttribute serviceBehavior = description.Behaviors.Find<ServiceBehaviorAttribute>();
  1712. object serviceInstanceUsedAsABehavior = serviceBehavior.GetWellKnownSingleton();
  1713. if (serviceInstanceUsedAsABehavior == null)
  1714. {
  1715. serviceInstanceUsedAsABehavior = serviceBehavior.GetHiddenSingleton();
  1716. this.disposableInstance = serviceInstanceUsedAsABehavior as IDisposable;
  1717. }
  1718. if ((typeof(IServiceBehavior).IsAssignableFrom(this.serviceType) || typeof(IContractBehavior).IsAssignableFrom(this.serviceType))
  1719. && serviceInstanceUsedAsABehavior == null)
  1720. {
  1721. serviceInstanceUsedAsABehavior = ServiceDescription.CreateImplementation(this.serviceType);
  1722. this.disposableInstance = serviceInstanceUsedAsABehavior as IDisposable;
  1723. }
  1724. if (this.SingletonInstance == null)
  1725. {
  1726. if (serviceInstanceUsedAsABehavior is IServiceBehavior)
  1727. {
  1728. description.Behaviors.Add((IServiceBehavior)serviceInstanceUsedAsABehavior);
  1729. }
  1730. }
  1731. ReflectedContractCollection reflectedContracts = new ReflectedContractCollection();
  1732. List<Type> interfaces = ServiceReflector.GetInterfaces(this.serviceType);
  1733. for (int i = 0; i < interfaces.Count; i++)
  1734. {
  1735. Type contractType = interfaces[i];
  1736. if (!reflectedContracts.Contains(contractType))
  1737. {
  1738. ContractDescription contract = null;
  1739. if (serviceInstanceUsedAsABehavior != null)
  1740. {
  1741. contract = ContractDescription.GetContract(contractType, serviceInstanceUsedAsABehavior);
  1742. }
  1743. else
  1744. {
  1745. contract = ContractDescription.GetContract(contractType, this.serviceType);
  1746. }
  1747. reflectedContracts.Add(contract);
  1748. Collection<ContractDescription> inheritedContracts = contract.GetInheritedContracts();
  1749. for (int j = 0; j < inheritedContracts.Count; j++)
  1750. {
  1751. ContractDescription inheritedContract = inheritedContracts[j];
  1752. if (!reflectedContracts.Contains(inheritedContract.ContractType))
  1753. {
  1754. reflectedContracts.Add(inheritedContract);
  1755. }
  1756. }
  1757. }
  1758. }
  1759. this.reflectedContracts = reflectedContracts;
  1760. implementedContracts = reflectedContracts.ToImplementedContracts();
  1761. return description;
  1762. }
  1763. protected void InitializeDescription(object singletonInstance, UriSchemeKeyedCollection baseAddresses)
  1764. {
  1765. if (singletonInstance == null)
  1766. {
  1767. throw new ArgumentNullException("singletonInstance");
  1768. }
  1769. this.singletonInstance = singletonInstance;
  1770. InitializeDescription(singletonInstance.GetType(), baseAddresses);
  1771. }
  1772. protected void InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses)
  1773. {
  1774. if (serviceType == null)
  1775. {
  1776. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceType"));
  1777. }
  1778. this.serviceType = serviceType;
  1779. base.InitializeDescription(baseAddresses);
  1780. }
  1781. protected override void OnClosed()
  1782. {
  1783. base.OnClosed();
  1784. if (this.disposableInstance != null)
  1785. {
  1786. this.disposableInstance.Dispose();
  1787. }
  1788. }
  1789. class ReflectedContractCollection : KeyedCollection<Type, ContractDescription>
  1790. {
  1791. public ReflectedContractCollection()
  1792. : base(null, 4)
  1793. {
  1794. }
  1795. protected override Type GetKeyForItem(ContractDescription item)
  1796. {
  1797. if (item == null)
  1798. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
  1799. return item.ContractType;
  1800. }
  1801. public IDictionary<string, ContractDescription> ToImplementedContracts()
  1802. {
  1803. Dictionary<string, ContractDescription> implementedContracts = new Dictionary<string, ContractDescription>();
  1804. foreach (ContractDescription contract in this.Items)
  1805. {
  1806. implementedContracts.Add(GetConfigKey(contract), contract);
  1807. }
  1808. return implementedContracts;
  1809. }
  1810. internal static string GetConfigKey(ContractDescription contract)
  1811. {
  1812. return contract.ConfigurationName;
  1813. }
  1814. }
  1815. class ReflectedAndBehaviorContractCollection
  1816. {
  1817. ReflectedContractCollection reflectedContracts;
  1818. KeyedByTypeCollection<IServiceBehavior> behaviors;
  1819. public ReflectedAndBehaviorContractCollection(ReflectedContractCollection reflectedContracts, KeyedByTypeCollection<IServiceBehavior> behaviors)
  1820. {
  1821. this.reflectedContracts = reflectedContracts;
  1822. this.behaviors = behaviors;
  1823. }
  1824. internal bool Contains(Type implementedContract)
  1825. {
  1826. if (this.reflectedContracts.Contains(implementedContract))
  1827. {
  1828. return true;
  1829. }
  1830. if (this.behaviors.Contains(typeof(ServiceMetadataBehavior)) && ServiceMetadataBehavior.IsMetadataImplementedType(implementedContract))
  1831. {
  1832. return true;
  1833. }
  1834. return false;
  1835. }
  1836. internal string GetConfigKey(Type implementedContract)
  1837. {
  1838. if (this.reflectedContracts.Contains(implementedContract))
  1839. {
  1840. return ReflectedContractCollection.GetConfigKey(reflectedContracts[implementedContract]);
  1841. }
  1842. if (this.behaviors.Contains(typeof(ServiceMetadataBehavior)) && ServiceMetadataBehavior.IsMetadataImplementedType(implementedContract))
  1843. {
  1844. return ServiceMetadataBehavior.MexContractName;
  1845. }
  1846. Fx.Assert("Calls to GetConfigKey are preceeded by calls to Contains.");
  1847. #pragma warning suppress 56506 // implementedContract is never null at this point
  1848. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SfxReflectedContractKeyNotFound2, implementedContract.FullName, string.Empty)));
  1849. }
  1850. }
  1851. }
  1852. }