-
-
Notifications
You must be signed in to change notification settings - Fork 833
/
ComponentRegistry.cs
364 lines (316 loc) · 14.1 KB
/
ComponentRegistry.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
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// http://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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Autofac.Builder;
using Autofac.Features.Decorators;
using Autofac.Util;
namespace Autofac.Core.Registration
{
/// <summary>
/// Maps services onto the components that provide them.
/// </summary>
/// <remarks>
/// The component registry provides services directly from components,
/// and also uses <see cref="IRegistrationSource"/> to generate components
/// on-the-fly or as adapters for other components. A component registry
/// is normally used through a <see cref="ContainerBuilder"/>, and not
/// directly by application code.
/// </remarks>
public class ComponentRegistry : Disposable, IComponentRegistry
{
/// <summary>
/// Protects instance variables from concurrent access.
/// </summary>
private readonly object _synchRoot = new object();
/// <summary>
/// External registration sources.
/// </summary>
private readonly List<IRegistrationSource> _dynamicRegistrationSources = new List<IRegistrationSource>();
/// <summary>
/// All registrations.
/// </summary>
private readonly List<IComponentRegistration> _registrations = new List<IComponentRegistration>();
/// <summary>
/// Keeps track of the status of registered services.
/// </summary>
private readonly Dictionary<Service, ServiceRegistrationInfo> _serviceInfo = new Dictionary<Service, ServiceRegistrationInfo>();
private readonly ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>> _decorators
= new ConcurrentDictionary<IComponentRegistration, IEnumerable<IComponentRegistration>>();
/// <summary>
/// Initializes a new instance of the <see cref="ComponentRegistry"/> class.
/// </summary>
public ComponentRegistry()
: this(new Dictionary<string, object>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ComponentRegistry"/> class.
/// </summary>
/// <param name="properties">The properties used during component registration.</param>
internal ComponentRegistry(IDictionary<string, object> properties)
{
Properties = properties;
}
/// <summary>
/// Gets the set of properties used during component registration.
/// </summary>
/// <value>
/// An <see cref="IDictionary{TKey, TValue}"/> that can be used to share
/// context across registrations.
/// </value>
public IDictionary<string, object> Properties { 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)
{
foreach (var registration in _registrations)
registration.Dispose();
base.Dispose(disposing);
}
/// <summary>
/// Attempts to find a default registration for the specified service.
/// </summary>
/// <param name="service">The service to look up.</param>
/// <param name="registration">The default registration for the service.</param>
/// <returns>True if a registration exists.</returns>
public bool TryGetRegistration(Service service, out IComponentRegistration registration)
{
if (service == null) throw new ArgumentNullException(nameof(service));
lock (_synchRoot)
{
var info = GetInitializedServiceInfo(service);
return info.TryGetRegistration(out registration);
}
}
/// <summary>
/// Determines whether the specified service is registered.
/// </summary>
/// <param name="service">The service to test.</param>
/// <returns>True if the service is registered.</returns>
public bool IsRegistered(Service service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
lock (_synchRoot)
{
return GetInitializedServiceInfo(service).IsRegistered;
}
}
/// <summary>
/// Register a component.
/// </summary>
/// <param name="registration">The component registration.</param>
public void Register(IComponentRegistration registration)
{
Register(registration, false);
}
/// <summary>
/// Register a component.
/// </summary>
/// <param name="registration">The component registration.</param>
/// <param name="preserveDefaults">If true, existing defaults for the services provided by the
/// component will not be changed.</param>
public void Register(IComponentRegistration registration, bool preserveDefaults)
{
if (registration == null) throw new ArgumentNullException(nameof(registration));
lock (_synchRoot)
{
AddRegistration(registration, preserveDefaults);
UpdateInitialisedAdapters(registration);
}
}
private void UpdateInitialisedAdapters(IComponentRegistration registration)
{
var adapterServices = new List<Service>();
foreach (var serviceInfo in _serviceInfo)
{
if (serviceInfo.Value.ShouldRecalculateAdaptersOn(registration))
{
adapterServices.Add(serviceInfo.Key);
}
}
if (adapterServices.Count == 0)
return;
Debug.WriteLine(
string.Format(
CultureInfo.InvariantCulture,
"[Autofac] Component '{0}' provides services that have already been adapted. Consider refactoring to ContainerBuilder.Build() rather than Update().",
registration));
var adaptationSandbox = new AdaptationSandbox(
_dynamicRegistrationSources.Where(rs => rs.IsAdapterForIndividualComponents),
registration,
adapterServices);
// Adapter registrations come from sources, so they are added with originatedFromSource: true
var adapters = adaptationSandbox.GetAdapters();
foreach (var adapter in adapters)
AddRegistration(adapter, true, true);
}
protected virtual void AddRegistration(IComponentRegistration registration, bool preserveDefaults, bool originatedFromSource = false)
{
foreach (var service in registration.Services)
{
var info = GetServiceInfo(service);
info.AddImplementation(registration, preserveDefaults, originatedFromSource);
}
_registrations.Add(registration);
var handler = Registered;
handler?.Invoke(this, new ComponentRegisteredEventArgs(this, registration));
}
/// <summary>
/// Gets the registered components.
/// </summary>
public IEnumerable<IComponentRegistration> Registrations
{
get
{
lock (_synchRoot)
return _registrations.ToArray();
}
}
/// <summary>
/// Selects from the available registrations after ensuring that any
/// dynamic registration sources that may provide <paramref name="service"/>
/// have been invoked.
/// </summary>
/// <param name="service">The service for which registrations are sought.</param>
/// <returns>Registrations supporting <paramref name="service"/>.</returns>
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
lock (_synchRoot)
{
var info = GetInitializedServiceInfo(service);
return info.Implementations.ToArray();
}
}
/// <inheritdoc />
public IEnumerable<IComponentRegistration> DecoratorsFor(IComponentRegistration registration)
{
if (registration == null) throw new ArgumentNullException(nameof(registration));
return _decorators.GetOrAdd(registration, r =>
{
foreach (var service in r.Services)
{
if (service is DecoratorService || !(service is IServiceWithType swt)) continue;
var decoratorService = new DecoratorService(swt.ServiceType);
return RegistrationsFor(decoratorService)
.OrderBy(d => d.GetRegistrationOrder())
.ToArray();
}
return Enumerable.Empty<IComponentRegistration>();
});
}
/// <summary>
/// Fired whenever a component is registered - either explicitly or via a
/// <see cref="IRegistrationSource"/>.
/// </summary>
public event EventHandler<ComponentRegisteredEventArgs> Registered;
/// <summary>
/// Add a registration source that will provide registrations on-the-fly.
/// </summary>
/// <param name="source">The source to register.</param>
public void AddRegistrationSource(IRegistrationSource source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
lock (_synchRoot)
{
_dynamicRegistrationSources.Insert(0, source);
foreach (var serviceRegistrationInfo in _serviceInfo)
serviceRegistrationInfo.Value.Include(source);
var handler = RegistrationSourceAdded;
handler?.Invoke(this, new RegistrationSourceAddedEventArgs(this, source));
}
}
/// <summary>
/// Gets the registration sources that are used by the registry.
/// </summary>
public IEnumerable<IRegistrationSource> Sources
{
get
{
lock (_synchRoot)
{
return _dynamicRegistrationSources.ToArray();
}
}
}
/// <summary>
/// Gets a value indicating whether the registry contains its own components.
/// True if the registry contains its own components; false if it is forwarding
/// registrations from another external registry.
/// </summary>
/// <remarks>This property is used when walking up the scope tree looking for
/// registrations for a new customised scope.</remarks>
public bool HasLocalComponents => true;
/// <summary>
/// Fired when an <see cref="IRegistrationSource"/> is added to the registry.
/// </summary>
public event EventHandler<RegistrationSourceAddedEventArgs> RegistrationSourceAdded;
private ServiceRegistrationInfo GetInitializedServiceInfo(Service service)
{
var info = GetServiceInfo(service);
if (info.IsInitialized)
return info;
if (!info.IsInitializing)
info.BeginInitialization(_dynamicRegistrationSources);
while (info.HasSourcesToQuery)
{
var next = info.DequeueNextSource();
foreach (var provided in next.RegistrationsFor(service, RegistrationsFor))
{
// This ensures that multiple services provided by the same
// component share a single component (we don't re-query for them)
foreach (var additionalService in provided.Services)
{
var additionalInfo = GetServiceInfo(additionalService);
if (additionalInfo.IsInitialized || additionalInfo == info) continue;
if (!additionalInfo.IsInitializing)
additionalInfo.BeginInitialization(_dynamicRegistrationSources.Where(src => src != next));
else
additionalInfo.SkipSource(next);
}
AddRegistration(provided, true, true);
}
}
info.CompleteInitialization();
return info;
}
private ServiceRegistrationInfo GetServiceInfo(Service service)
{
ServiceRegistrationInfo existing;
if (_serviceInfo.TryGetValue(service, out existing))
return existing;
var info = new ServiceRegistrationInfo(service);
_serviceInfo.Add(service, info);
return info;
}
}
}