/
ServiceRegistry.cs
596 lines (501 loc) · 20.8 KB
/
ServiceRegistry.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// ------------------------------------------------------------------------------------------------
// <copyright file="ServiceRegistry.cs" company="Microsoft">
// Copyright 2013 Will Perry, Microsoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// ------------------------------------------------------------------------------------------------
namespace WillPe.Utils
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Xml;
/// <summary>
/// A simple inversion of control helper
/// </summary>
public sealed class ServiceRegistry : IDisposable
{
private static readonly ServiceRegistry instance = new ServiceRegistry();
private readonly IDictionary<Type, Binding> bindings = new Dictionary<Type, Binding>();
private readonly ServiceRegistryEventSource log;
private readonly object syncRoot = new object();
private bool disposed;
private ServiceRegistry()
{
this.log = new ServiceRegistryEventSource();
}
~ServiceRegistry()
{
this.Dispose(false);
}
public static ServiceRegistry Instance
{
get { return ServiceRegistry.instance; }
}
public IDictionary<Type, Type> Bindings
{
get { return this.bindings.ToDictionary(b => b.Key, b => b.Value.ConcreteType); }
}
public EventSource Log
{
get { return this.log; }
}
/// <summary>
/// Registers <typeparamref name="TConcrete"/> as the default implementation
/// of <typeparamref name="TAbstract"/>
/// </summary>
/// <typeparam name="TAbstract">The abstract type or interface.</typeparam>
/// <typeparam name="TConcrete">The concrete type.</typeparam>
public void Bind<TAbstract, TConcrete>() where TConcrete : class, TAbstract
{
this.Bind(typeof(TAbstract), typeof(TConcrete));
}
/// <summary>
/// Registers <paramref name="concreteType"/> as the default implementation
/// of <paramref name="abstractType"/>.
/// </summary>
/// <param name="abstractType">The abstract type or interface.</param>
/// <param name="concreteType">The concrete type.</param>
public void Bind(Type abstractType, Type concreteType)
{
if (abstractType == null)
{
throw new ArgumentNullException("abstractType");
}
if (concreteType == null)
{
throw new ArgumentNullException("concreteType");
}
this.AddOrUpdateBinding(abstractType, concreteType);
}
/// <summary>
/// Registers <paramref name="singleton"/> as the singleton implementation
/// of <typeparamref name="TAbstract"/>.
/// </summary>
/// <typeparam name="TAbstract">The abstract type or interface.</typeparam>
/// <param name="singleton">The singleton.</param>
public void Bind<TAbstract>(TAbstract singleton)
{
this.Bind(typeof(TAbstract), singleton);
}
/// <summary>
/// Registers <paramref name="singleton"/> as the singleton implementation
/// of <paramref name="abstractType"/>.
/// </summary>
/// <param name="abstractType">The abstract type or interface.</param>
/// <param name="singleton">The singleton.</param>
public void Bind(Type abstractType, object singleton)
{
if (abstractType == null)
{
throw new ArgumentNullException("abstractType");
}
if (singleton == null)
{
throw new ArgumentNullException("singleton");
}
this.AddOrUpdateBinding(abstractType, singleton);
}
/// <summary>
/// Discards any bindings from the Service Registry
/// </summary>
public void Clear()
{
this.log.Clear(this.bindings.Count);
lock (this.syncRoot)
{
this.bindings.Clear();
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Gets or creates an instance of the concrete class registered for <typeparamref name="TAbstract"/>.
/// </summary>
public TAbstract Get<TAbstract>(params object[] args)
{
return (TAbstract)this.Get(typeof(TAbstract), args);
}
/// <summary>
/// Gets or creates an instance of the concrete class registered for abstractType.
/// </summary>
public object Get(Type abstractType, params object[] args)
{
var argTypes = new Type[0];
if (args != null && args.Length > 0)
{
argTypes = args.Select(a => a.GetType()).ToArray();
}
return this.Get(abstractType, argTypes, args);
}
/// <summary>
/// Gets or creates an instance of the concrete class registered for <typeparamref name="TAbstract"/>
/// if a binding is found. Returns null otherwise.
/// </summary>
public TAbstract Find<TAbstract>(params object[] args)
{
return (TAbstract)this.Find(typeof(TAbstract), args);
}
/// <summary>
/// Gets or creates an instance of the concrete class registered for abstractType if a
/// binding is found. Returns null otherwise.
/// </summary>
public object Find(Type abstractType, params object[] args)
{
var argTypes = new Type[0];
if (args != null && args.Length > 0)
{
argTypes = args.Select(a => a.GetType()).ToArray();
}
return this.Get(abstractType, argTypes, args, throwOnError: false);
}
/// <summary>
/// Tries to get or create an instance of the concrete class registered for <typeparamref name="TAbstract"/>
/// if a binding is found.
/// </summary>
public bool TryGet<TAbstract>(out TAbstract value, params object[] args)
{
value = default(TAbstract);
object temp;
if (this.TryGet(typeof(TAbstract), out temp, args))
{
value = (TAbstract)temp;
return true;
}
return false;
}
/// <summary>
/// Tries to get or create an instance of the concrete class registered for abstractType if a
/// binding is found.
/// </summary>
public bool TryGet(Type abstractType, out object value, params object[] args)
{
var argTypes = new Type[0];
if (args != null && args.Length > 0)
{
argTypes = args.Select(a => a.GetType()).ToArray();
}
value = this.Get(abstractType, argTypes, args, throwOnError: false);
return value != null;
}
public void Init(XmlElement configuration)
{
this.log.Initializing();
// Sample configuration:
// <serviceRegistry>
// <bindings>
// <clear />
// <add abstract="Microsoft.Test.ServiceBus.Push.Service.Hosting.HostingEnvironment, Microsoft.Test.ServiceBus.Push.Service"
// concrete="Microsoft.Test.ServiceBus.Push.Service.AzureHost.AzureHostingEnvironment, Microsoft.Test.ServiceBus.Push.Service.AzureHost" />
// <add abstract="Microsoft.Test.ServiceBus.Push.Service.Hosting.HostingContainerFactory, Microsoft.Test.ServiceBus.Push.Service"
// concrete="Microsoft.Test.ServiceBus.Push.Service.Hosting.HostingContainerFactory, Microsoft.Test.ServiceBus.Push.Service" />
// </bindings>
// </serviceRegistry>
if (configuration == null || configuration.LocalName != "serviceRegistry")
{
this.log.InvalidConfigurationFragment();
throw new ArgumentException("The specififed configuration must be an element named serviceRegistry", "configuration");
}
var bindingConfigurations = configuration.SelectSingleNode("bindings");
if (bindingConfigurations != null)
{
foreach (var bindingConfiguration in bindingConfigurations.OfType<XmlElement>())
{
switch (bindingConfiguration.LocalName.ToLowerInvariant())
{
case "clear":
this.Clear();
break;
case "add":
this.AddBindingFromConfig(bindingConfiguration);
break;
default:
throw new NotSupportedException("The binding directive '" + bindingConfiguration.LocalName + "' is unknown.");
}
}
}
}
/// <summary>
/// Reloads the Object Factory's configuration from app.config, discarding any bindings
/// which have been programatically set.
/// </summary>
public void Reset(XmlElement configuration = null)
{
this.Clear();
if (configuration != null)
{
this.Init(configuration);
}
}
/// <summary>
/// Removes any registration for creating instances of <typeparamref name="TAbstract"/>
/// </summary>
/// <typeparam name="TAbstract">The abstract type or interface.</typeparam>
public void Unbind<TAbstract>()
{
this.Unbind(typeof(TAbstract));
}
/// <summary>
/// Removes any registration for creating instances of <paramref name="abstractType"/>
/// </summary>
/// <param name="abstractType">The abstract type or interface.</param>
public void Unbind(Type abstractType)
{
this.RemoveBinding(abstractType);
}
private void AddBindingFromConfig(XmlElement bindingConfiguration)
{
var abstractTypeName = bindingConfiguration.GetAttribute("abstract");
if (string.IsNullOrEmpty(abstractTypeName))
{
throw new InvalidOperationException("Invalid binding configuration. The 'abstract' attribute is required (Element: '" + bindingConfiguration.OuterXml + "')");
}
var concreteTypeName = bindingConfiguration.GetAttribute("concrete");
if (string.IsNullOrEmpty(concreteTypeName))
{
throw new InvalidOperationException("Invalid binding configuration. The 'concrete' attribute is required (Element: '" + bindingConfiguration.OuterXml + "')");
}
var isSingletonAttribute = bindingConfiguration.GetAttribute("isSingleton");
var isSingleton = false;
if (!string.IsNullOrEmpty(isSingletonAttribute) && !bool.TryParse(isSingletonAttribute, out isSingleton))
{
throw new InvalidOperationException("Invalid binding configuration. If the optional 'isSingleton' is present, it must be 'true' or 'false' (Element: '" + bindingConfiguration.OuterXml + "')");
}
var abstractType = Type.GetType(abstractTypeName, true);
var concreteType = Type.GetType(concreteTypeName, true);
if (isSingleton)
{
var instance = Activator.CreateInstance(concreteType);
this.AddOrUpdateBinding(abstractType, instance);
}
else
{
this.AddOrUpdateBinding(abstractType, concreteType);
}
}
private void AddOrUpdateBinding(Type abstractType, Type concreteType)
{
this.log.SetBinding(abstractType.Name, concreteType.Name);
Binding binding;
lock (this.syncRoot)
{
if (!this.bindings.ContainsKey(abstractType))
{
this.bindings.Add(abstractType, new Binding(abstractType));
}
binding = this.bindings[abstractType];
}
binding.ConcreteType = concreteType;
}
private void AddOrUpdateBinding(Type abstractType, object singleton)
{
this.log.SetSingletonBinding(abstractType.Name, singleton.GetType().Name);
Binding binding;
lock (this.syncRoot)
{
if (!this.bindings.ContainsKey(abstractType))
{
this.bindings.Add(abstractType, new Binding(abstractType));
}
binding = this.bindings[abstractType];
}
binding.Singleton = singleton;
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// Dispose managed resources here
this.log.Dispose();
}
this.disposed = true;
}
}
private object Get(Type abstractType, Type[] constructorParameterTypes, object[] constructorParameters, bool throwOnError=true)
{
Binding binding;
lock (this.syncRoot)
{
if (!this.bindings.ContainsKey(abstractType))
{
this.log.BindingNotFound(abstractType.Name);
if (throwOnError)
{
throw new ArgumentException("There is no binding for abstract type: " + abstractType.Name + ". Consider adding one in the <serviceRegistry> section of the configuration file, or using ServiceRegistry.Bind to specify an implementation");
}
return null;
}
binding = this.bindings[abstractType];
}
return binding.GetInstance(constructorParameterTypes, constructorParameters);
}
private void RemoveBinding(Type abstractType)
{
this.log.ClearBinding(abstractType.Name);
lock (this.syncRoot)
{
if (this.bindings.ContainsKey(abstractType))
{
this.bindings.Remove(abstractType);
}
}
}
private sealed class Binding
{
private readonly Type abstractType;
private readonly object syncRoot;
private Type concreteType;
private object singleton;
public Binding(Type abstractType)
{
if (abstractType == null)
{
throw new ArgumentNullException("abstractType");
}
this.abstractType = abstractType;
this.syncRoot = new object();
}
public Type AbstractType
{
get { return this.abstractType; }
}
public Type ConcreteType
{
get { return this.concreteType; }
set { this.Bind(value); }
}
public bool IsSingleton { get; private set; }
public object Singleton
{
get { return this.concreteType; }
set { this.Bind(value); }
}
public void Bind(Type concrete)
{
if (concrete == null)
{
throw new ArgumentNullException("concrete");
}
if (!this.abstractType.IsAssignableFrom(concrete))
{
throw new ArgumentException(string.Format("{0} cannot be assigned to a variable of type {1}", concrete.Name, this.abstractType.Name));
}
lock (this.syncRoot)
{
this.IsSingleton = false;
this.concreteType = concrete;
this.singleton = null;
}
}
public void Bind(object singleton)
{
if (singleton == null)
{
throw new ArgumentNullException("singleton");
}
if (!this.abstractType.IsAssignableFrom(singleton.GetType()))
{
throw new ArgumentException(
string.Format("Object of type {0} cannot be assigned to a variable of type {1}", singleton.GetType().Name, this.abstractType.Name));
}
lock (this.syncRoot)
{
this.IsSingleton = true;
this.concreteType = singleton.GetType();
this.singleton = singleton;
}
}
public object GetInstance(Type[] constructorParameterTypes, object[] constructorParameters)
{
object singleton = null;
Type concreteType = null;
lock (this.syncRoot)
{
if (this.IsSingleton)
{
singleton = this.singleton;
}
else
{
if (this.concreteType == null)
{
throw new InvalidOperationException(
string.Format("The service registry is not configured to create instances for abstract/interface type '{0}'", this.abstractType.Name));
}
concreteType = this.concreteType;
}
}
if (singleton != null)
{
return singleton;
}
var constructor = concreteType.GetConstructor(constructorParameterTypes);
if (constructor == null)
{
var message = string.Format(
"An instance of type '{0}' cannot be created, because there is no constructor with parameter types ({1})",
this.concreteType.FullName,
string.Join(", ", constructorParameterTypes.Select(t => t.Name).ToArray()));
throw new InvalidOperationException(message);
}
return constructor.Invoke(constructorParameters);
}
}
[EventSource(Name = "ServiceRegistry")]
private sealed class ServiceRegistryEventSource : EventSource
{
[Event(5, Message = "Cannot find a binding for requested abstract type '{0}'.", Level = EventLevel.Warning)]
public void BindingNotFound(string abstractType)
{
this.WriteEvent(5, abstractType);
}
[Event(3, Message = "Clearing {0} binding(s)", Level = EventLevel.Informational)]
public void Clear(int count)
{
this.WriteEvent(3, count);
}
[Event(4, Message = "Clearing binding for '{0}'.", Level = EventLevel.Informational)]
public void ClearBinding(string abstractType)
{
this.WriteEvent(4, abstractType);
}
[Event(7, Message = "Initializing Service Registry from Xml Configuration", Level = EventLevel.Informational)]
public void Initializing()
{
this.WriteEvent(7);
}
[Event(6, Message = "The specified configuration fragment is invalid", Level = EventLevel.Warning)]
public void InvalidConfigurationFragment()
{
this.WriteEvent(6);
}
[Event(1, Message = "Binding '{0}' to '{1}'", Level = EventLevel.Informational)]
public void SetBinding(string abstractType, string concreteType)
{
this.WriteEvent(1, abstractType, concreteType);
}
[Event(2, Message = "Binding '{0}' to a singleton instance of '{1}'", Level = EventLevel.Informational)]
public void SetSingletonBinding(string abstractType, string concreteType)
{
this.WriteEvent(2, abstractType, concreteType);
}
}
}
}