-
-
Notifications
You must be signed in to change notification settings - Fork 833
/
ContainerBuilder.cs
252 lines (218 loc) · 10 KB
/
ContainerBuilder.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
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Autofac.Builder;
using Autofac.Core;
using Autofac.Core.Registration;
using Autofac.Features.Collections;
using Autofac.Features.GeneratedFactories;
using Autofac.Features.Indexed;
using Autofac.Features.LazyDependencies;
using Autofac.Features.Metadata;
using Autofac.Features.OwnedInstances;
namespace Autofac;
/// <summary>
/// Used to build an <see cref="IContainer"/> from component registrations.
/// </summary>
/// <example>
/// <code>
/// var builder = new ContainerBuilder();
///
/// builder.RegisterType<Logger>()
/// .As<ILogger>()
/// .SingleInstance();
///
/// builder.Register(c => new MessageHandler(c.Resolve<ILogger>()));
///
/// var container = builder.Build();
/// // resolve components from container...
/// </code>
/// </example>
/// <remarks>Most <see cref="ContainerBuilder"/> functionality is accessed
/// via extension methods in <see cref="RegistrationExtensions"/>.</remarks>
/// <seealso cref="IContainer"/>
/// <see cref="RegistrationExtensions"/>
public sealed class ContainerBuilder
{
private static int _builderAlreadyAllocated;
private readonly bool _clearRegistrationCaches;
private readonly List<DeferredCallback> _configurationCallbacks = new List<DeferredCallback>();
private BuildCallbackService? _buildCallbacks;
private bool _wasBuilt;
/// <summary>
/// Initializes a new instance of the <see cref="ContainerBuilder"/> class.
/// </summary>
public ContainerBuilder()
: this(new Dictionary<string, object?>())
{
// If this is not the first container builder we have constructed in this process,
// it's entirely likely we are going to create more (for example, in unit tests).
// So, all container builders after the first will preserve cache's that
// only have the RegistrationCacheUsage.Registration flag, to improve
// the performance of subsequent container builds.
_clearRegistrationCaches = IsFirstContainerBuilder();
}
/// <summary>
/// Initializes a new instance of the <see cref="ContainerBuilder"/> class.
/// </summary>
/// <param name="properties">The properties used during component registration.</param>
internal ContainerBuilder(IDictionary<string, object?> properties)
: this(properties, new ComponentRegistryBuilder(new DefaultRegisteredServicesTracker(), properties))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContainerBuilder"/> class.
/// </summary>
/// <param name="componentRegistryBuilder">The builder to use for building the underlying <see cref="IComponentRegistry" />.</param>
internal ContainerBuilder(IComponentRegistryBuilder componentRegistryBuilder)
: this(new Dictionary<string, object?>(), componentRegistryBuilder)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ContainerBuilder"/> class.
/// </summary>
/// <param name="properties">The properties used during component registration.</param>
/// <param name="componentRegistryBuilder">The builder to use for building the underlying <see cref="IComponentRegistry" />.</param>
internal ContainerBuilder(IDictionary<string, object?> properties, IComponentRegistryBuilder componentRegistryBuilder)
{
Properties = properties;
ComponentRegistryBuilder = componentRegistryBuilder;
}
/// <summary>
/// Gets the builder to use for building the underlying <see cref="IComponentRegistry" />.
/// </summary>
public IComponentRegistryBuilder ComponentRegistryBuilder { get; }
/// <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>
/// Register a callback that will be invoked when the container is configured.
/// </summary>
/// <remarks>This is primarily for extending the builder syntax.</remarks>
/// <param name="configurationCallback">Callback to execute.</param>
public DeferredCallback RegisterCallback(Action<IComponentRegistryBuilder> configurationCallback)
{
if (configurationCallback == null)
{
throw new ArgumentNullException(nameof(configurationCallback));
}
var c = new DeferredCallback(configurationCallback);
_configurationCallbacks.Add(c);
return c;
}
/// <summary>
/// Register a callback that will be invoked when the container (or lifetime scope) is built.
/// </summary>
/// <param name="buildCallback">Callback to execute.</param>
/// <returns>The <see cref="ContainerBuilder"/> instance to continue registration calls.</returns>
/// <remarks>
/// The argument to the registered build callback will be an instance of the derived <see cref="IContainer" /> if this
/// builder is being used to build a fresh container, or an <see cref="ILifetimeScope" /> if it's being used to
/// create custom registrations for a new lifetime scope.
/// </remarks>
public ContainerBuilder RegisterBuildCallback(Action<ILifetimeScope> buildCallback)
{
if (buildCallback == null)
{
throw new ArgumentNullException(nameof(buildCallback));
}
if (_buildCallbacks == null)
{
_buildCallbacks = new BuildCallbackService();
// Register the service.
this.RegisterInstance(_buildCallbacks);
}
_buildCallbacks.AddCallback(buildCallback);
return this;
}
/// <summary>
/// Create a new container with the component registrations that have been made.
/// </summary>
/// <param name="options">Options that influence the way the container is initialized.</param>
/// <remarks>
/// Build can only be called once per <see cref="ContainerBuilder"/>
/// - this prevents ownership issues for provided instances.
/// Build enables support for the relationship types that come with Autofac (e.g.
/// Func, Owned, Meta, Lazy, IEnumerable.) To exclude support for these types,
/// first create the container, then call Update() on the builder.
/// </remarks>
/// <returns>A new container with the configured component registrations.</returns>
public IContainer Build(ContainerBuildOptions options = ContainerBuildOptions.None)
{
Properties[MetadataKeys.ContainerBuildOptions] = options;
#pragma warning disable CA2000 // Dispose objects before losing scope
ComponentRegistryBuilder.Register(new SelfComponentRegistration());
#pragma warning restore CA2000 // Dispose objects before losing scope
Build(ComponentRegistryBuilder, (options & ContainerBuildOptions.ExcludeDefaultModules) != ContainerBuildOptions.None);
var componentRegistry = ComponentRegistryBuilder.Build();
var result = new Container(componentRegistry);
if ((options & ContainerBuildOptions.IgnoreStartableComponents) == ContainerBuildOptions.None)
{
StartableManager.StartStartableComponents(Properties, result);
}
// Run any build callbacks.
BuildCallbackManager.RunBuildCallbacks(result);
// Allow the reflection cache to empty any registration-time caches to save memory.
ReflectionCacheSet.Shared.OnContainerBuildClearCaches(_clearRegistrationCaches);
return result;
}
/// <summary>
/// Configure an existing registry with the component registrations
/// that have been made. Primarily useful in dynamically adding registrations
/// to a child lifetime scope.
/// </summary>
/// <remarks>
/// Update can only be called once per <see cref="ContainerBuilder"/>
/// - this prevents ownership issues for provided instances.
/// </remarks>
/// <param name="componentRegistry">An existing registry to make the registrations in.</param>
internal void UpdateRegistry(IComponentRegistryBuilder componentRegistry)
{
if (componentRegistry == null)
{
throw new ArgumentNullException(nameof(componentRegistry));
}
Build(componentRegistry, true);
}
private void Build(IComponentRegistryBuilder componentRegistry, bool excludeDefaultModules)
{
if (componentRegistry == null)
{
throw new ArgumentNullException(nameof(componentRegistry));
}
if (_wasBuilt)
{
throw new InvalidOperationException(ContainerBuilderResources.BuildCanOnlyBeCalledOnce);
}
_wasBuilt = true;
if (!excludeDefaultModules)
{
RegisterDefaultAdapters(componentRegistry);
}
foreach (var callback in _configurationCallbacks)
{
callback.Callback(componentRegistry);
}
}
private void RegisterDefaultAdapters(IComponentRegistryBuilder componentRegistry)
{
this.RegisterGeneric(typeof(KeyedServiceIndex<,>)).As(typeof(IIndex<,>)).InstancePerLifetimeScope();
componentRegistry.AddRegistrationSource(new CollectionRegistrationSource());
componentRegistry.AddRegistrationSource(new OwnedInstanceRegistrationSource());
componentRegistry.AddRegistrationSource(new MetaRegistrationSource());
componentRegistry.AddRegistrationSource(new LazyRegistrationSource());
componentRegistry.AddRegistrationSource(new LazyWithMetadataRegistrationSource());
componentRegistry.AddRegistrationSource(new StronglyTypedMetaRegistrationSource());
componentRegistry.AddRegistrationSource(new GeneratedFactoryRegistrationSource());
}
private static bool IsFirstContainerBuilder()
{
// First container will start with a value of 0, we will try and set it to 1;
// if the value is 0, it means it's the first builder.
return Interlocked.CompareExchange(ref _builderAlreadyAllocated, 1, 0) == 0;
}
}