-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectContainer.cs
More file actions
457 lines (417 loc) · 20.3 KB
/
ObjectContainer.cs
File metadata and controls
457 lines (417 loc) · 20.3 KB
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
// =================================================================================================================================
// Copyright (c) RapidField LLC. Licensed under the MIT License. See LICENSE.txt in the project root for license information.
// =================================================================================================================================
using Microsoft.Extensions.Configuration;
using RapidField.SolidInstruments.Core;
using RapidField.SolidInstruments.Core.ArgumentValidation;
using RapidField.SolidInstruments.Core.Extensions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace RapidField.SolidInstruments.ObjectComposition
{
/// <summary>
/// Manages object creation, storage, resolution and disposal for a related group of object instances.
/// </summary>
/// <remarks>
/// <see cref="ObjectContainer" /> is the default implementation of <see cref="IObjectContainer" />.
/// </remarks>
public sealed class ObjectContainer : ConfigurableInstrument<ObjectContainerConfiguration>, IObjectContainer
{
/// <summary>
/// Initializes a new instance of the <see cref="ObjectContainer" /> class.
/// </summary>
/// <param name="factoryConfigurator">
/// An action that configures the object factory for the container.
/// </param>
/// <param name="definitionConfigurator">
/// An action that configures the request-product type pair definitions for the container.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="factoryConfigurator" /> is <see langword="null" /> -or- <paramref name="definitionConfigurator" /> is
/// <see langword="null" />.
/// </exception>
public ObjectContainer(Action<IObjectFactoryConfigurationProductionFunctions> factoryConfigurator, Action<IObjectContainerConfigurationDefinitions> definitionConfigurator)
: this(InitializeFactory(DefaultConfiguration, factoryConfigurator.RejectIf().IsNull()), definitionConfigurator)
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectContainer" /> class.
/// </summary>
/// <param name="factory">
/// A factory that produces objects for the container.
/// </param>
/// <param name="definitionConfigurator">
/// An action that configures the request-product type pair definitions for the container.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="definitionConfigurator" /> is <see langword="null" /> -or- <paramref name="factory" /> is
/// <see langword="null" />.
/// </exception>
public ObjectContainer(IObjectFactory factory, Action<IObjectContainerConfigurationDefinitions> definitionConfigurator)
: this(DefaultConfiguration, factory, definitionConfigurator, false)
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectContainer" /> class.
/// </summary>
/// <param name="applicationConfiguration">
/// Configuration information for the application.
/// </param>
/// <param name="factory">
/// A factory that produces objects for the container.
/// </param>
/// <param name="definitionConfigurator">
/// An action that configures the request-product type pair definitions for the container.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationConfiguration" /> is <see langword="null" /> -or- <paramref name="definitionConfigurator" />
/// is <see langword="null" /> -or- <paramref name="factory" /> is <see langword="null" />.
/// </exception>
public ObjectContainer(IConfiguration applicationConfiguration, IObjectFactory factory, Action<IObjectContainerConfigurationDefinitions> definitionConfigurator)
: this(applicationConfiguration, factory, definitionConfigurator, false)
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="ObjectContainer" /> class.
/// </summary>
/// <param name="applicationConfiguration">
/// Configuration information for the application.
/// </param>
/// <param name="factory">
/// A factory that produces objects for the container.
/// </param>
/// <param name="definitionConfigurator">
/// An action that configures the request-product type pair definitions for the container.
/// </param>
/// <param name="managesFactory">
/// A valued that indicates whether or not <paramref name="factory" /> is managed by the container.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationConfiguration" /> is <see langword="null" /> -or- <paramref name="definitionConfigurator" />
/// is <see langword="null" /> -or- <paramref name="factory" /> is <see langword="null" />.
/// </exception>
[DebuggerHidden]
private ObjectContainer(IConfiguration applicationConfiguration, IObjectFactory factory, Action<IObjectContainerConfigurationDefinitions> definitionConfigurator, Boolean managesFactory)
: base(applicationConfiguration)
{
DefinitionConfigurator = definitionConfigurator.RejectIf().IsNull(nameof(definitionConfigurator));
Factory = factory.RejectIf().IsNull(nameof(factory)).TargetArgument;
LazyInstanceDictionary = new Lazy<IDictionary<Type, Object>>(InitializeInstanceDictionary, LazyThreadSafetyMode.ExecutionAndPublication);
LazyInstanceGroup = new Lazy<IFactoryProducedInstanceGroup>(InitializeInstanceGroup, LazyThreadSafetyMode.PublicationOnly);
ManagesFactory = managesFactory;
}
/// <summary>
/// Returns the instance of specified type that is managed by the current <see cref="ObjectContainer" />.
/// </summary>
/// <typeparam name="T">
/// The type of the instance to return.
/// </typeparam>
/// <returns>
/// The instance of specified type that is managed by the current <see cref="ObjectContainer" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <typeparamref name="T" /> is not a supported type for the group.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The object is disposed.
/// </exception>
/// <exception cref="ObjectProductionException">
/// An exception was raised during object production.
/// </exception>
public T Get<T>()
where T : class
{
var requestType = typeof(T);
using (var controlToken = StateControl.Enter())
{
RejectIfDisposed();
try
{
if (Registrations.ContainsKey(requestType) == false)
{
throw new ArgumentException($"{requestType.FullName} is not a registered request type.", nameof(T));
}
}
catch (ObjectConfigurationException exception)
{
throw new ObjectProductionException(requestType, exception);
}
var productType = Registrations[requestType].ProductType;
if (Factory.SupportedProductTypes.Contains(productType) == false)
{
throw new ArgumentException($"{productType.FullName} is not a registered product type.", nameof(T));
}
T lazyProduct;
try
{
var lazyInitializer = InstanceDictionary[requestType];
var lazyValueProperty = lazyInitializer.GetType().GetProperty(nameof(Lazy<T>.Value));
lazyProduct = lazyValueProperty.GetValue(lazyInitializer) as T;
}
catch (Exception exception)
{
throw new ObjectProductionException(requestType, exception);
}
if (lazyProduct is null)
{
throw new ArgumentException("The factory does not support the registered types.", nameof(T));
}
return lazyProduct;
}
}
/// <summary>
/// Returns a new instance of specified type that is managed by the current <see cref="ObjectContainer" />.
/// </summary>
/// <remarks>
/// <see cref="GetNew{T}" /> differs from <see cref="Get{T}" /> in that it returns a distinct instance for every subsequent
/// call.
/// </remarks>
/// <typeparam name="T">
/// The type of the instance to return.
/// </typeparam>
/// <returns>
/// The instance of specified type that is managed by the current <see cref="ObjectContainer" />.
/// </returns>
/// <exception cref="ArgumentException">
/// <typeparamref name="T" /> is not a supported type for the group.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The object is disposed.
/// </exception>
/// <exception cref="ObjectProductionException">
/// An exception was raised during object production.
/// </exception>
public T GetNew<T>()
where T : class
{
RejectIfDisposed();
var requestType = typeof(T);
try
{
if (Registrations.ContainsKey(requestType) == false)
{
throw new ArgumentException($"{requestType.FullName} is not a registered request type.", nameof(T));
}
var productType = Registrations[requestType].ProductType;
var getNewMethod = InstanceGroup.GetType().GetMethod(nameof(InstanceGroup.GetNew), Array.Empty<Type>()).MakeGenericMethod(productType);
if (!(getNewMethod.Invoke(InstanceGroup, Array.Empty<Object>()) is T newProduct))
{
throw new ArgumentException("The factory does not support the registered types.", nameof(T));
}
return newProduct;
}
catch (ArgumentException)
{
throw;
}
catch (ObjectProductionException)
{
throw;
}
catch (Exception exception)
{
throw new ObjectProductionException(requestType, exception);
}
}
/// <summary>
/// Configures the current <see cref="ObjectContainer" />.
/// </summary>
/// <param name="configuration">
/// Configuration information for the current <see cref="ObjectContainer" />.
/// </param>
protected sealed override void Configure(ObjectContainerConfiguration configuration) => DefinitionConfigurator(configuration.Definitions);
/// <summary>
/// Releases all resources consumed by the current <see cref="ObjectContainer" />.
/// </summary>
/// <param name="disposing">
/// A value indicating whether or not managed resources should be released.
/// </param>
protected override void Dispose(Boolean disposing)
{
try
{
if (disposing)
{
LazyInstanceGroup?.Dispose();
if (ManagesFactory)
{
Factory?.Dispose();
}
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Initializes and configures a new <see cref="IObjectFactory" /> for the container.
/// </summary>
/// <param name="applicationConfiguration">
/// Configuration information for the application.
/// </param>
/// <param name="factoryConfigurator">
/// An action that configures the object factory for the container.
/// </param>
/// <returns>
/// A new <see cref="IObjectFactory" /> for the container.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationConfiguration" /> is <see langword="null" />.
/// </exception>
[DebuggerHidden]
private static IObjectFactory InitializeFactory(IConfiguration applicationConfiguration, Action<IObjectFactoryConfigurationProductionFunctions> factoryConfigurator) => new ContainerObjectFactory(applicationConfiguration, factoryConfigurator);
/// <summary>
/// Gets a collection of managed object instances.
/// </summary>
/// <returns>
/// A collection of managed object instances.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The object container is not configured or the factory does not support the registered types.
/// </exception>
[DebuggerHidden]
private IDictionary<Type, Object> InitializeInstanceDictionary()
{
var instanceDictionary = new ConcurrentDictionary<Type, Object>();
try
{
foreach (var definition in Registrations.Values)
{
var getLazyMethodInfo = InstanceGroup.GetType().GetMethod(nameof(InstanceGroup.GetLazy)).MakeGenericMethod(definition.ProductType);
var lazyInstance = getLazyMethodInfo.Invoke(InstanceGroup, Array.Empty<Object>());
instanceDictionary.AddOrUpdate(definition.RequestType, lazyInstance, (key, oldValue) => lazyInstance);
}
}
catch (Exception exception)
{
throw new InvalidOperationException($"The object container is not configured or the factory does not support the registered types. See inner exception.", exception);
}
return instanceDictionary;
}
/// <summary>
/// Initializes an object that manages creation and lifetime of instances for the current <see cref="ObjectContainer" />.
/// </summary>
/// <returns>
/// An object that manages creation and lifetime of instances for the current <see cref="ObjectContainer" />.
/// </returns>
[DebuggerHidden]
private IFactoryProducedInstanceGroup InitializeInstanceGroup() => new FactoryProducedInstanceGroup(Factory);
/// <summary>
/// Gets the types of the instances that are managed by the current <see cref="ObjectContainer" />.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The object is disposed.
/// </exception>
public IEnumerable<Type> InstanceTypes
{
get
{
foreach (var instanceType in Registrations.Keys)
{
RejectIfDisposed();
yield return instanceType;
}
}
}
/// <summary>
/// Gets a collection of request-product type pairs that constitute the configured definitions for the container.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IDictionary<Type, IObjectContainerDefinition> Registrations => ((ObjectContainerConfigurationDefinitions)Configuration.Definitions).Registrations;
/// <summary>
/// Gets a collection of managed object instances.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The object container is not configured or the factory does not support the registered types.
/// </exception>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IDictionary<Type, Object> InstanceDictionary => LazyInstanceDictionary.Value;
/// <summary>
/// Gets an object that manages creation and lifetime of instances for the current <see cref="ObjectContainer" />.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IFactoryProducedInstanceGroup InstanceGroup => LazyInstanceGroup.Value;
/// <summary>
/// Represents an action that configures the request-product type pair definitions for the container.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Action<IObjectContainerConfigurationDefinitions> DefinitionConfigurator;
/// <summary>
/// Represents an factory that produces objects for the current <see cref="ObjectContainer" />.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly IObjectFactory Factory;
/// <summary>
/// Represents a lazily-initialized collection of managed object instances.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Lazy<IDictionary<Type, Object>> LazyInstanceDictionary;
/// <summary>
/// Represents a lazily-initialized object that manages creation and lifetime of instances for the current
/// <see cref="ObjectContainer" />.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Lazy<IFactoryProducedInstanceGroup> LazyInstanceGroup;
/// <summary>
/// Represents a valued that indicates whether or not the current <see cref="ObjectContainer" /> manages
/// <see cref="Factory" />.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Boolean ManagesFactory;
/// <summary>
/// Represents the default <see cref="IObjectFactory" /> that is used to produce object instances for
/// <see cref="ObjectContainer" /> instances.
/// </summary>
private sealed class ContainerObjectFactory : ObjectFactory
{
/// <summary>
/// Initializes a new instance of the <see cref="ContainerObjectFactory" /> class.
/// </summary>
/// <param name="applicationConfiguration">
/// Configuration information for the application.
/// </param>
/// <param name="factoryConfigurator">
/// An action that configures the object factory.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationConfiguration" /> is <see langword="null" />.
/// </exception>
[DebuggerHidden]
internal ContainerObjectFactory(IConfiguration applicationConfiguration, Action<IObjectFactoryConfigurationProductionFunctions> factoryConfigurator)
: base(applicationConfiguration)
{
FactoryConfigurator = new Action<IObjectFactoryConfigurationProductionFunctions<Object>>((functions) =>
{
factoryConfigurator(new ObjectFactoryConfigurationProductionFunctions(functions));
});
}
/// <summary>
/// Configures the current <see cref="ContainerObjectFactory" />.
/// </summary>
/// <param name="configuration">
/// Configuration information for the current <see cref="ContainerObjectFactory" />.
/// </param>
protected sealed override void Configure(ObjectFactoryConfiguration configuration) => FactoryConfigurator(configuration.ProductionFunctions);
/// <summary>
/// Releases all resources consumed by the current <see cref="ContainerObjectFactory" />.
/// </summary>
/// <param name="disposing">
/// A value indicating whether or not managed resources should be released.
/// </param>
protected override void Dispose(Boolean disposing) => base.Dispose(disposing);
/// <summary>
/// Represents an action that configures the object factory.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Action<IObjectFactoryConfigurationProductionFunctions<Object>> FactoryConfigurator;
}
}
}