-
-
Notifications
You must be signed in to change notification settings - Fork 833
/
LifetimeScope.cs
443 lines (383 loc) · 18 KB
/
LifetimeScope.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
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// https://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Autofac.Builder;
using Autofac.Core.Registration;
using Autofac.Core.Resolving;
using Autofac.Util;
namespace Autofac.Core.Lifetime
{
/// <summary>
/// Lifetime scope implementation.
/// </summary>
[DebuggerDisplay("Tag = {Tag}, IsDisposed = {IsDisposed}")]
[SuppressMessage("Microsoft.ApiDesignGuidelines", "CA2213", Justification = "The creator of the parent lifetime scope is responsible for disposal.")]
public class LifetimeScope : Disposable, ISharingLifetimeScope, IServiceProvider
{
/// <summary>
/// Protects shared instances from concurrent access. Other members and the base class are threadsafe.
/// </summary>
private readonly object _synchRoot = new object();
private readonly ConcurrentDictionary<Guid, object> _sharedInstances = new ConcurrentDictionary<Guid, object>();
private object? _anonymousTag;
private LifetimeScope? parentScope;
internal static Guid SelfRegistrationId { get; } = Guid.NewGuid();
/// <summary>
/// The tag applied to root scopes when no other tag is specified.
/// </summary>
public static readonly object RootTag = "root";
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private object MakeAnonymousTag() => _anonymousTag = new object();
/// <summary>
/// Initializes a new instance of the <see cref="LifetimeScope"/> class.
/// </summary>
/// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
/// <param name="componentRegistry">Components used in the scope.</param>
/// <param name="parent">Parent scope.</param>
protected LifetimeScope(IComponentRegistry componentRegistry, LifetimeScope parent, object tag)
: this(componentRegistry, tag)
{
parentScope = parent ?? throw new ArgumentNullException(nameof(parent));
RootLifetimeScope = parentScope.RootLifetimeScope;
}
/// <summary>
/// Initializes a new instance of the <see cref="LifetimeScope"/> class.
/// </summary>
/// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
/// <param name="componentRegistry">Components used in the scope.</param>
public LifetimeScope(IComponentRegistry componentRegistry, object tag)
{
_sharedInstances[SelfRegistrationId] = this;
ComponentRegistry = componentRegistry ?? throw new ArgumentNullException(nameof(componentRegistry));
Tag = tag ?? throw new ArgumentNullException(nameof(tag));
RootLifetimeScope = this;
}
/// <summary>
/// Initializes a new instance of the <see cref="LifetimeScope"/> class.
/// </summary>
/// <param name="componentRegistry">Components used in the scope.</param>
public LifetimeScope(IComponentRegistry componentRegistry)
: this(componentRegistry, RootTag)
{
}
/// <summary>
/// Begin a new anonymous sub-scope. Instances created via the sub-scope
/// will be disposed along with it.
/// </summary>
/// <returns>A new lifetime scope.</returns>
public ILifetimeScope BeginLifetimeScope()
{
return BeginLifetimeScope(MakeAnonymousTag());
}
/// <summary>
/// Begin a new tagged sub-scope. Instances created via the sub-scope
/// will be disposed along with it.
/// </summary>
/// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
/// <returns>A new lifetime scope.</returns>
public ILifetimeScope BeginLifetimeScope(object tag)
{
CheckNotDisposed();
CheckTagIsUnique(tag);
var scope = new LifetimeScope(ComponentRegistry, this, tag);
RaiseBeginning(scope);
return scope;
}
private void CheckTagIsUnique(object tag)
{
if (ReferenceEquals(tag, _anonymousTag)) return;
ISharingLifetimeScope parentScope = this;
while (parentScope != RootLifetimeScope)
{
// In the scope where we are searching for parents, then the parent scope will not be null.
if (parentScope.Tag.Equals(tag))
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.DuplicateTagDetected, tag));
}
// In the scope of searching for tags, the ParentLifetimeScope will always be set.
parentScope = parentScope.ParentLifetimeScope!;
}
}
[SuppressMessage("CA1030", "CA1030", Justification = "This method raises the event; it's not the event proper.")]
private void RaiseBeginning(ILifetimeScope scope)
{
var handler = ChildLifetimeScopeBeginning;
handler?.Invoke(this, new LifetimeScopeBeginningEventArgs(scope));
}
/// <summary>
/// Begin a new anonymous sub-scope, with additional components available to it.
/// Component instances created via the new scope
/// will be disposed along with it.
/// </summary>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
/// that adds component registrations visible only in the new scope.</param>
/// <returns>A new lifetime scope.</returns>
/// <example>
/// <code>
/// IContainer cr = // ...
/// using (var lifetime = cr.BeginLifetimeScope(builder => {
/// builder.RegisterType<Foo>();
/// builder.RegisterType<Bar>().As<IBar>(); })
/// {
/// var foo = lifetime.Resolve<Foo>();
/// }
/// </code>
/// </example>
public ILifetimeScope BeginLifetimeScope(Action<ContainerBuilder> configurationAction)
{
return BeginLifetimeScope(MakeAnonymousTag(), configurationAction);
}
/// <summary>
/// Begin a new tagged sub-scope, with additional components available to it.
/// Component instances created via the new scope
/// will be disposed along with it.
/// </summary>
/// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
/// that adds component registrations visible only in the new scope.</param>
/// <returns>A new lifetime scope.</returns>
/// <example>
/// <code>
/// IContainer cr = // ...
/// using (var lifetime = cr.BeginLifetimeScope("unitOfWork", builder => {
/// builder.RegisterType<Foo>();
/// builder.RegisterType<Bar>().As<IBar>(); })
/// {
/// var foo = lifetime.Resolve<Foo>();
/// }
/// </code>
/// </example>
public ILifetimeScope BeginLifetimeScope(object tag, Action<ContainerBuilder> configurationAction)
{
if (configurationAction == null) throw new ArgumentNullException(nameof(configurationAction));
CheckNotDisposed();
CheckTagIsUnique(tag);
var localsBuilder = CreateScopeRestrictedRegistry(tag, configurationAction);
var scope = new LifetimeScope(localsBuilder.Build(), this, tag);
scope.Disposer.AddInstanceForDisposal(localsBuilder);
if (localsBuilder.Properties.TryGetValue(MetadataKeys.ContainerBuildOptions, out var options)
&& options != null
&& !((ContainerBuildOptions)options).HasFlag(ContainerBuildOptions.IgnoreStartableComponents))
{
StartableManager.StartStartableComponents(localsBuilder.Properties, scope);
}
// Run any build callbacks.
BuildCallbackManager.RunBuildCallbacks(scope);
RaiseBeginning(scope);
return scope;
}
/// <summary>
/// Creates and setup the registry for a child scope.
/// </summary>
/// <param name="tag">The tag applied to the <see cref="ILifetimeScope"/>.</param>
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
/// that adds component registrations visible only in the child scope.</param>
/// <returns>Registry to use for a child scope.</returns>
/// <remarks>It is the responsibility of the caller to make sure that the registry is properly
/// disposed of. This is generally done by adding the registry to the <see cref="Disposer"/>
/// property of the child scope.</remarks>
private IComponentRegistryBuilder CreateScopeRestrictedRegistry(object tag, Action<ContainerBuilder> configurationAction)
{
var restrictedRootScopeLifetime = new MatchingScopeLifetime(tag);
var tracker = new ScopeRestrictedRegisteredServicesTracker(restrictedRootScopeLifetime);
var fallbackProperties = new FallbackDictionary<string, object?>(ComponentRegistry.Properties);
var registryBuilder = new ComponentRegistryBuilder(tracker, fallbackProperties);
var builder = new ContainerBuilder(fallbackProperties, registryBuilder);
foreach (var source in ComponentRegistry.Sources)
{
if (source.IsAdapterForIndividualComponents)
builder.RegisterSource(source);
}
// Issue #272: Only the most nested parent registry with HasLocalComponents is registered as an external source
// It provides all non-adapting registrations from itself and from it's parent registries
ISharingLifetimeScope? parent = this;
while (parent != null)
{
if (parent.ComponentRegistry.HasLocalComponents)
{
var externalSource = new ExternalRegistrySource(parent.ComponentRegistry);
builder.RegisterSource(externalSource);
break;
}
parent = parent.ParentLifetimeScope;
}
configurationAction(builder);
builder.UpdateRegistry(registryBuilder);
return registryBuilder;
}
/// <inheritdoc />
public object ResolveComponent(ResolveRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
CheckNotDisposed();
var operation = new ResolveOperation(this);
var handler = ResolveOperationBeginning;
handler?.Invoke(this, new ResolveOperationBeginningEventArgs(operation));
return operation.Execute(request);
}
/// <summary>
/// Gets the parent of this node of the hierarchy, or null.
/// </summary>
public ISharingLifetimeScope? ParentLifetimeScope => parentScope;
/// <summary>
/// Gets the root of the sharing hierarchy.
/// </summary>
public ISharingLifetimeScope RootLifetimeScope { get; }
/// <summary>
/// Try to create an instance with a GUID key.
/// </summary>
/// <param name="id">Key.</param>
/// <param name="creator">Creation function.</param>
/// <returns>An instance.</returns>
public object CreateSharedInstance(Guid id, Func<object> creator)
{
if (creator == null) throw new ArgumentNullException(nameof(creator));
lock (_synchRoot)
{
if (_sharedInstances.TryGetValue(id, out var result)) return result;
result = creator();
if (_sharedInstances.ContainsKey(id))
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, LifetimeScopeResources.SelfConstructingDependencyDetected, result.GetType().FullName));
_sharedInstances.TryAdd(id, result);
return result;
}
}
/// <summary>
/// Try to retrieve an instance based on a GUID key.
/// </summary>
/// <param name="id">Key to look up.</param>
/// <param name="value">The instance that has the specified key.</param>
/// <returns>true if the key was found; otherwise, false.</returns>
public bool TryGetSharedInstance(Guid id, out object value)
{
return _sharedInstances.TryGetValue(id, out value);
}
/// <summary>
/// Gets the disposer associated with this container. Instances can be associated
/// with it manually if required.
/// </summary>
public IDisposer Disposer { get; } = new Disposer();
/// <summary>
/// Gets the tag applied to the lifetime scope.
/// </summary>
/// <remarks>The tag applied to this scope and the contexts generated when
/// it resolves component dependencies.</remarks>
public object Tag { get; }
/// <summary>
/// Gets the services associated with the components that provide them.
/// </summary>
public IComponentRegistry ComponentRegistry { get; }
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
var handler = CurrentScopeEnding;
try
{
handler?.Invoke(this, new LifetimeScopeEndingEventArgs(this));
}
finally
{
Disposer.Dispose();
}
// ReSharper disable once InconsistentlySynchronizedField
_sharedInstances.Clear();
parentScope = null;
}
base.Dispose(disposing);
}
protected override async ValueTask DisposeAsync(bool disposing)
{
if (disposing)
{
var handler = CurrentScopeEnding;
try
{
handler?.Invoke(this, new LifetimeScopeEndingEventArgs(this));
}
finally
{
await Disposer.DisposeAsync();
}
// ReSharper disable once InconsistentlySynchronizedField
_sharedInstances.Clear();
parentScope = null;
}
// Don't call the base (which would just call the normal Dispose).
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckNotDisposed()
{
if (IsTreeDisposed())
throw new ObjectDisposedException(LifetimeScopeResources.ScopeIsDisposed, innerException: null);
}
/// <summary>
/// Gets a value indicating whether this or any of the parent disposables have been disposed.
/// </summary>
/// <returns>true if this instance of any of the parent instances have been disposed.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsTreeDisposed()
{
return IsDisposed || (parentScope is object && parentScope.IsTreeDisposed());
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object
/// to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.-or- null if there is
/// no service object of type <paramref name="serviceType"/>.
/// </returns>
public object? GetService(Type serviceType)
{
if (serviceType == null) throw new ArgumentNullException(nameof(serviceType));
return this.ResolveOptional(serviceType);
}
/// <summary>
/// Fired when a new scope based on the current scope is beginning.
/// </summary>
public event EventHandler<LifetimeScopeBeginningEventArgs>? ChildLifetimeScopeBeginning;
/// <summary>
/// Fired when this scope is ending.
/// </summary>
public event EventHandler<LifetimeScopeEndingEventArgs>? CurrentScopeEnding;
/// <summary>
/// Fired when a resolve operation is beginning in this scope.
/// </summary>
public event EventHandler<ResolveOperationBeginningEventArgs>? ResolveOperationBeginning;
}
}