-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
MicrosoftDependencyResolver.cs
348 lines (297 loc) · 11.8 KB
/
MicrosoftDependencyResolver.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
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection;
namespace Splat.Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Microsoft DI implementation for <see cref="IDependencyResolver"/>.
/// </summary>
/// <seealso cref="IDependencyResolver" />
[SuppressMessage("Globalization", "CA1303", Justification = "Unnecessary warning")]
public class MicrosoftDependencyResolver : IDependencyResolver
{
private const string MutableExceptionMessage = "The container has not yet been built.";
private const string ImmutableExceptionMessage = "This container has already been built and cannot be modified.";
private static readonly Type _dictionaryType = typeof(ContractDictionary<>);
private IServiceCollection _serviceCollection;
private bool _isImmutable;
private IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MicrosoftDependencyResolver" /> class with an <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">An instance of <see cref="IServiceCollection"/>.</param>
public MicrosoftDependencyResolver(IServiceCollection services = null)
{
_serviceCollection = services ?? new ServiceCollection();
}
/// <summary>
/// Initializes a new instance of the <see cref="MicrosoftDependencyResolver" /> class with a configured service Provider.
/// </summary>
/// <param name="serviceProvider">A ready to use service provider.</param>
public MicrosoftDependencyResolver(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
_serviceProvider = serviceProvider;
_isImmutable = true;
}
/// <summary>
/// Gets the internal Microsoft conainer,
/// or build new if this instance was not initialized with one.
/// </summary>
protected virtual IServiceProvider ServiceProvider
{
get
{
if (_serviceProvider == null)
{
_serviceProvider = _serviceCollection.BuildServiceProvider();
}
return _serviceProvider;
}
}
/// <inheritdoc />
public virtual object GetService(Type serviceType, string contract = null) =>
GetServices(serviceType, contract).LastOrDefault();
/// <inheritdoc />
public virtual IEnumerable<object> GetServices(Type serviceType, string contract = null)
{
var isNull = serviceType == null;
if (isNull)
{
serviceType = typeof(NullServiceType);
}
IEnumerable<object> services;
if (string.IsNullOrWhiteSpace(contract))
{
services = ServiceProvider.GetServices(serviceType);
if (isNull)
{
services = services
.Cast<NullServiceType>()
.Select(nst => nst.Factory());
}
}
else
{
var dic = GetContractDictionary(serviceType, false);
services = dic?
.GetFactories(contract)
.Select(f => f());
}
return services;
}
/// <inheritdoc />
public virtual void Register(Func<object> factory, Type serviceType, string contract = null)
{
if (_isImmutable)
{
throw new InvalidOperationException(ImmutableExceptionMessage);
}
var isNull = serviceType == null;
if (isNull)
{
serviceType = typeof(NullServiceType);
}
if (string.IsNullOrWhiteSpace(contract))
{
_serviceCollection.AddTransient(serviceType, _ =>
isNull
? new NullServiceType(factory)
: factory());
}
else
{
var dic = GetContractDictionary(serviceType, true);
dic.AddFactory(contract, factory);
}
// required so that it gets rebuilt if not injected externally.
_serviceProvider = null;
}
/// <inheritdoc/>
public virtual void UnregisterCurrent(Type serviceType, string contract = null)
{
if (_isImmutable)
{
throw new InvalidOperationException(ImmutableExceptionMessage);
}
if (serviceType == null)
{
serviceType = typeof(NullServiceType);
}
if (contract == null)
{
var sd = _serviceCollection.LastOrDefault(s => s.ServiceType == serviceType);
_serviceCollection.Remove(sd);
}
else
{
var dic = GetContractDictionary(serviceType, false);
if (dic != null)
{
dic.RemoveLastFactory(contract);
if (dic.IsEmpty)
{
RemoveContractService(serviceType);
}
}
}
// required so that it gets rebuilt if not injected externally.
_serviceProvider = null;
}
/// <summary>
/// Unregisters all the values associated with the specified type and contract - or -
/// If the container has already been built, removes the specified contract (scope) entirely,
/// ignoring the <paramref name="serviceType"/> argument.
/// </summary>
/// <param name="serviceType">The service type to unregister.</param>
/// <param name="contract">This parameter is ignored. Service will be removed from all contracts.</param>
public virtual void UnregisterAll(Type serviceType, string contract = null)
{
if (_isImmutable)
{
throw new InvalidOperationException(ImmutableExceptionMessage);
}
if (serviceType == null)
{
serviceType = typeof(NullServiceType);
}
if (contract == null)
{
var sds = _serviceCollection
.Where(s => s.ServiceType == serviceType)
.ToList();
foreach (var sd in sds)
{
_serviceCollection.Remove(sd);
}
}
else
{
var dic = GetContractDictionary(serviceType, false);
if (dic != null && dic.TryRemoveContract(contract) && dic.IsEmpty)
{
RemoveContractService(serviceType);
}
}
// required so that it gets rebuilt if not injected externally.
_serviceProvider = null;
}
/// <inheritdoc />
public virtual IDisposable ServiceRegistrationCallback(Type serviceType, string contract, Action<IDisposable> callback)
{
// this method is not used by RxUI
throw new NotImplementedException();
}
/// <inheritdoc/>
public virtual bool HasRegistration(Type serviceType)
{
if (serviceType == null)
{
serviceType = typeof(NullServiceType);
}
if (!_isImmutable)
{
return _serviceCollection.Any(sd => sd.ServiceType == serviceType);
}
var service = _serviceProvider.GetService(serviceType);
return service != null;
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes of the instance.
/// </summary>
/// <param name="disposing">Whether or not the instance is disposing.</param>
protected virtual void Dispose(bool disposing)
{
}
private static Type GetDictionaryType(Type serviceType) => _dictionaryType.MakeGenericType(serviceType);
private void RemoveContractService(Type serviceType)
{
var dicType = GetDictionaryType(serviceType);
var sd = _serviceCollection.SingleOrDefault(s => s.ServiceType == serviceType);
_serviceCollection.Remove(sd);
}
private ContractDictionary GetContractDictionary(Type serviceType, bool createIfNotExists)
{
var dicType = GetDictionaryType(serviceType);
if (_isImmutable)
{
return (ContractDictionary)ServiceProvider.GetService(dicType);
}
var dic = _serviceCollection
.Where(sd => sd.ServiceType == dicType)
.Select(sd => sd.ImplementationInstance)
.Cast<ContractDictionary>()
.SingleOrDefault();
if (createIfNotExists && dic == null)
{
dic = (ContractDictionary)Activator.CreateInstance(dicType);
_serviceCollection.AddSingleton(dicType, dic);
}
return dic;
}
private class ContractDictionary
{
private readonly ConcurrentDictionary<string, IList<Func<object>>> _dictionary = new ConcurrentDictionary<string, IList<Func<object>>>();
public bool IsEmpty => _dictionary.Count == 0;
public bool TryRemoveContract(string contract) =>
_dictionary.TryRemove(contract, out var _);
public Func<object> GetFactory(string contract) =>
GetFactories(contract)
.LastOrDefault();
public IEnumerable<Func<object>> GetFactories(string contract) =>
_dictionary.TryGetValue(contract, out var collection)
? collection
: Enumerable.Empty<Func<object>>();
public void AddFactory(string contract, Func<object> factory) =>
_dictionary.AddOrUpdate(contract, _ => new List<Func<object>> { factory }, (_, list) =>
{
list.Add(factory);
return list;
});
public void RemoveLastFactory(string contract) =>
_dictionary.AddOrUpdate(contract, default(IList<Func<object>>), (_, list) =>
{
var lastIndex = list.Count - 1;
if (lastIndex > 0)
{
list.RemoveAt(lastIndex);
}
// TODO if list empty remove contract entirely
// need to find how to atomically update or remove
// https://github.com/dotnet/corefx/issues/24246
return list;
});
}
private class ContractDictionary<T> : ContractDictionary
{
}
private class NullServiceType
{
public NullServiceType(Func<object> factory)
{
Factory = factory;
}
public Func<object> Factory { get; }
}
}
}