-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
TestServiceProvider.cs
278 lines (234 loc) · 8.83 KB
/
TestServiceProvider.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
using System.Collections;
namespace Bunit;
/// <summary>
/// Represents a <see cref="IServiceProvider"/> and <see cref="IServiceCollection"/>
/// as a single type used for test purposes.
/// </summary>
#if !NET8_0_OR_GREATER
public sealed class TestServiceProvider : IServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable
#else
public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable
#endif
{
private static readonly ServiceProviderOptions DefaultServiceProviderOptions = new() { ValidateScopes = true };
private readonly IServiceCollection serviceCollection;
private IServiceProvider? rootServiceProvider;
private IServiceScope? serviceScope;
private IServiceProvider? serviceProvider;
private IServiceProvider? fallbackServiceProvider;
private ServiceProviderOptions options = DefaultServiceProviderOptions;
private Func<IServiceProvider> serviceProviderFactory;
/// <summary>
/// Gets a value indicating whether this <see cref="TestServiceProvider"/> has been initialized, and
/// no longer will accept calls to the <c>AddService</c>'s methods.
/// </summary>
public bool IsProviderInitialized => serviceProvider is not null;
/// <inheritdoc/>
public int Count => serviceCollection.Count;
/// <inheritdoc/>
public bool IsReadOnly => IsProviderInitialized || serviceCollection.IsReadOnly;
/// <inheritdoc/>
public ServiceDescriptor this[int index]
{
get => serviceCollection[index];
set
{
CheckInitializedAndThrow();
serviceCollection[index] = value;
}
}
/// <summary>
/// Gets or sets the <see cref="ServiceProviderOptions"/> used when the <see cref="IServiceProvider"/> is created.
/// </summary>
public ServiceProviderOptions Options
{
get => options;
set => options = value ?? DefaultServiceProviderOptions;
}
/// <summary>
/// Initializes a new instance of the <see cref="TestServiceProvider"/> class
/// and sets its service collection to the provided <paramref name="initialServiceCollection"/>, if any.
/// </summary>
public TestServiceProvider(IServiceCollection? initialServiceCollection = null)
: this(initialServiceCollection ?? new ServiceCollection(), initializeProvider: false)
{
}
private TestServiceProvider(IServiceCollection initialServiceCollection, bool initializeProvider)
{
serviceCollection = initialServiceCollection;
serviceProviderFactory = () => serviceCollection.BuildServiceProvider(Options);
if (initializeProvider)
InitializeProvider();
}
/// <summary>
/// Use a custom service provider factory for creating the underlying IServiceProvider.
/// </summary>
/// <param name="serviceProviderFactory">custom service provider factory</param>
public void UseServiceProviderFactory(Func<IServiceCollection, IServiceProvider> serviceProviderFactory)
{
if (serviceProviderFactory is null)
{
throw new ArgumentNullException(nameof(serviceProviderFactory));
}
this.serviceProviderFactory = () => serviceProviderFactory(serviceCollection);
}
/// <summary>
/// Use a custom service provider factory for creating the underlying IServiceProvider.
/// </summary>
/// <typeparam name="TContainerBuilder">
/// Type of the container builder.
/// See <see cref="IServiceProviderFactory{TContainerBuilder}" />
/// </typeparam>
/// <param name="serviceProviderFactory">custom service provider factory</param>
/// <param name="configure">builder configuration action</param>
public void UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> serviceProviderFactory, Action<TContainerBuilder>? configure = null) where TContainerBuilder : notnull
{
if (serviceProviderFactory is null)
{
throw new ArgumentNullException(nameof(serviceProviderFactory));
}
UseServiceProviderFactory(serviceCollection =>
{
var containerBuilder = serviceProviderFactory.CreateBuilder(serviceCollection);
configure?.Invoke(containerBuilder);
return serviceProviderFactory.CreateServiceProvider(containerBuilder);
});
}
/// <summary>
/// Creates the underlying service provider. Throws if it was already build.
/// Automatically called while getting a service if uninitialized.
/// No longer will accept calls to the <c>AddService</c>'s methods.
/// See <see cref="IsProviderInitialized"/>
/// </summary>
[MemberNotNull(nameof(serviceProvider))]
private void InitializeProvider()
{
CheckInitializedAndThrow();
serviceCollection.AddSingleton<TestServiceProvider>(this);
rootServiceProvider = serviceProviderFactory.Invoke();
serviceScope = rootServiceProvider.CreateScope();
serviceProvider = serviceScope.ServiceProvider;
}
/// <summary>
/// Add a fall back service provider that provides services when the default returns null.
/// </summary>
/// <param name="serviceProvider">The fallback service provider.</param>
public void AddFallbackServiceProvider(IServiceProvider serviceProvider)
=> fallbackServiceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
/// <summary>
/// Get service of type T from the test provider.
/// </summary>
/// <typeparam name="TService">The type of service object to get.</typeparam>
/// <returns>A service object of type T or null if there is no such service.</returns>
public TService? GetService<TService>() => (TService?)GetService(typeof(TService))!;
#if NETSTANDARD2_1
/// <inheritdoc/>
[return: MaybeNull]
public object GetService(Type serviceType)
=> GetServiceInternal(serviceType);
#else
/// <inheritdoc/>
public object? GetService(Type serviceType)
=> GetServiceInternal(serviceType);
#endif
private object? GetServiceInternal(Type serviceType)
{
if (serviceProvider is null)
InitializeProvider();
var result = serviceProvider.GetService(serviceType);
if (result is null && fallbackServiceProvider is not null)
result = fallbackServiceProvider.GetService(serviceType);
return result;
}
/// <inheritdoc/>
public IEnumerator<ServiceDescriptor> GetEnumerator() => serviceCollection.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc/>
public void Dispose()
{
if (serviceScope is IDisposable serviceScopeDisposable)
serviceScopeDisposable.Dispose();
if (rootServiceProvider is IDisposable rootServiceProviderDisposable)
rootServiceProviderDisposable.Dispose();
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
if (serviceScope is IAsyncDisposable serviceScopeAsync)
await serviceScopeAsync.DisposeAsync();
if (rootServiceProvider is IAsyncDisposable rootServiceProviderAsync)
await rootServiceProviderAsync.DisposeAsync();
}
/// <inheritdoc/>
public int IndexOf(ServiceDescriptor item) => serviceCollection.IndexOf(item);
/// <inheritdoc/>
public void Insert(int index, ServiceDescriptor item)
{
CheckInitializedAndThrow();
serviceCollection.Insert(index, item);
}
/// <inheritdoc/>
public void RemoveAt(int index)
{
CheckInitializedAndThrow();
serviceCollection.RemoveAt(index);
}
/// <inheritdoc/>
public void Add(ServiceDescriptor item)
{
CheckInitializedAndThrow();
serviceCollection.Add(item);
}
/// <inheritdoc/>
public void Clear()
{
CheckInitializedAndThrow();
serviceCollection.Clear();
}
/// <inheritdoc/>
public bool Contains(ServiceDescriptor item) => serviceCollection.Contains(item);
/// <inheritdoc/>
public void CopyTo(ServiceDescriptor[] array, int arrayIndex) => serviceCollection.CopyTo(array, arrayIndex);
/// <inheritdoc/>
public bool Remove(ServiceDescriptor item)
{
CheckInitializedAndThrow();
return serviceCollection.Remove(item);
}
#if NET8_0_OR_GREATER
/// <inheritdoc/>
public object? GetKeyedService(Type serviceType, object? serviceKey)
{
if (serviceProvider is null)
InitializeProvider();
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
var value = keyedServiceProvider.GetKeyedService(serviceType, serviceKey);
if (value is not null)
return value;
}
if (fallbackServiceProvider is IKeyedServiceProvider fallbackKeyedServiceProvider)
return fallbackKeyedServiceProvider.GetKeyedService(serviceType, serviceKey);
return default;
}
/// <inheritdoc/>
public object GetRequiredKeyedService(Type serviceType, object? serviceKey)
{
var service = GetKeyedService(serviceType, serviceKey) ?? throw new InvalidOperationException($"No service for type '{serviceType}' and key '{serviceKey}' has been registered.");
return service;
}
#endif
private void CheckInitializedAndThrow()
{
if (IsProviderInitialized)
{
throw new InvalidOperationException(
"New services/implementations cannot be registered with the " +
"Services provider in a TestContext, after the first services has been retrieved " +
"from it using e.g. the GetService or GetRequiredService methods. " +
"This typically happens when a component is rendered, so make " +
"sure all services are added before that.");
}
}
}