/
AutofacDependencyResolver.cs
378 lines (334 loc) · 13.7 KB
/
AutofacDependencyResolver.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
// 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.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Autofac;
using Autofac.Core;
using Autofac.Core.Registration;
#pragma warning disable CS0618 // Obsolete values.
namespace Splat.Autofac
{
/// <summary>
/// Autofac implementation for <see cref="IDependencyResolver"/>.
/// </summary>
public class AutofacDependencyResolver : IDependencyResolver
{
private readonly object _lockObject = new object();
private IComponentContext _componentContext;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacDependencyResolver" /> class.
/// </summary>
/// <param name="componentContext">The component context.</param>
public AutofacDependencyResolver(IComponentContext componentContext)
{
_componentContext = componentContext;
}
/// <inheritdoc />
public virtual object GetService(Type serviceType, string contract = null)
{
lock (_lockObject)
{
return Resolve(serviceType, contract);
}
}
/// <inheritdoc />
public virtual IEnumerable<object> GetServices(Type serviceType, string contract = null)
{
lock (_lockObject)
{
try
{
var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
var instance = Resolve(enumerableType, contract);
return ((IEnumerable)instance).Cast<object>();
}
catch (DependencyResolutionException)
{
return null;
}
}
}
/// <inheritdoc />
public bool HasRegistration(Type serviceType, string contract = null)
{
lock (_lockObject)
{
return _componentContext.ComponentRegistry.Registrations.Any(x => GetWhetherServiceRegistrationMatchesSearch(
x.Services,
serviceType,
contract));
}
}
/// <summary>
/// Register a function with the resolver which will generate a object
/// for the specified service type.
/// Optionally a contract can be registered which will indicate
/// that that registration will only work with that contract.
/// Most implementations will use a stack based approach to allow for multile items to be registered.
/// </summary>
/// <param name="factory">The factory function which generates our object.</param>
/// <param name="serviceType">The type which is used for the registration.</param>
/// <param name="contract">A optional contract value which will indicates to only generate the value if this contract is specified.</param>
public virtual void Register(Func<object> factory, Type serviceType, string contract = null)
{
lock (_lockObject)
{
var builder = new ContainerBuilder();
if (string.IsNullOrEmpty(contract))
{
builder.Register(x => factory()).As(serviceType).AsImplementedInterfaces();
}
else
{
builder.Register(x => factory()).Named(contract, serviceType).AsImplementedInterfaces();
}
builder.Update(_componentContext.ComponentRegistry);
}
}
/// <summary>
/// Unregisters the current item based on the specified type and contract.
/// https://stackoverflow.com/questions/5091101/is-it-possible-to-remove-an-existing-registration-from-autofac-container-builder.
/// </summary>
/// <param name="serviceType">The service type to unregister.</param>
/// <param name="contract">The optional contract value, which will only remove the value associated with the contract.</param>
/// <exception cref="System.NotImplementedException">This is not implemented by default.</exception>
/// <inheritdoc />
public virtual void UnregisterCurrent(Type serviceType, string contract = null)
{
lock (_lockObject)
{
var registrations = _componentContext.ComponentRegistry.Registrations.ToList();
var registrationCount = registrations.Count;
if (registrationCount < 1)
{
return;
}
var candidatesForRemoval = new List<IComponentRegistration>(registrationCount);
var registrationIndex = 0;
while (registrationIndex < registrationCount)
{
var componentRegistration = registrations[registrationIndex];
var isCandidateForRemoval = GetWhetherServiceRegistrationMatchesSearch(
componentRegistration.Services,
serviceType,
contract);
if (isCandidateForRemoval)
{
registrations.RemoveAt(registrationIndex);
candidatesForRemoval.Add(componentRegistration);
registrationCount--;
}
else
{
registrationIndex++;
}
}
if (candidatesForRemoval.Count == 0)
{
// nothing to remove
return;
}
if (candidatesForRemoval.Count > 1)
{
// need to re-add some registrations
var reAdd = candidatesForRemoval.Take(candidatesForRemoval.Count - 1);
registrations.AddRange(reAdd);
/*
// check for multi service registration
// in future might want to just remove a single service from a component
// rather than do the whole component.
var lastCandidate = candidatesForRemoval.Last();
var lastCandidateRegisteredServices = lastCandidate.Services.ToArray();
if (lastCandidateRegisteredServices.Length > 1)
{
//
// builder.RegisterType<CallLogger>()
// .AsSelf()
// .As<ILogger>()
// .As<ICallInterceptor>();
var survivingServices = lastCandidateRegisteredServices.Where(s => s.GetType() != serviceType);
var newRegistration = new ComponentRegistration(
lastCandidate.Id,
lastCandidate.Activator,
lastCandidate.Lifetime,
lastCandidate.Sharing,
lastCandidate.Ownership,
survivingServices,
lastCandidate.Metadata);
registrations.Add(newRegistration);
}
*/
}
RemoveAndRebuild(registrations);
}
}
/// <summary>
/// Unregisters all the values associated with the specified type and contract.
/// https://stackoverflow.com/questions/5091101/is-it-possible-to-remove-an-existing-registration-from-autofac-container-builder.
/// </summary>
/// <param name="serviceType">The service type to unregister.</param>
/// <param name="contract">The optional contract value, which will only remove the value associated with the contract.</param>
/// <exception cref="System.NotImplementedException">This is not implemented by default.</exception>
/// <inheritdoc />
public virtual void UnregisterAll(Type serviceType, string contract = null)
{
lock (_lockObject)
{
// prevent multiple enumerations
var registrations = _componentContext.ComponentRegistry.Registrations.ToList();
var registrationCount = registrations.Count;
if (registrationCount < 1)
{
return;
}
if (!string.IsNullOrEmpty(contract))
{
RemoveAndRebuild(
registrationCount,
registrations,
x => x.Services.All(s =>
{
if (!(s is TypedService typedService))
{
return false;
}
return typedService.ServiceType != serviceType || !HasMatchingContract(s, contract);
}));
return;
}
RemoveAndRebuild(
registrationCount,
registrations,
x => x.Services.All(s =>
{
if (!(s is TypedService typedService))
{
return false;
}
return typedService.ServiceType != serviceType;
}));
}
}
/// <inheritdoc />
public virtual IDisposable ServiceRegistrationCallback(Type serviceType, string contract, Action<IDisposable> callback)
{
// this method is not used by RxUI
throw new NotImplementedException();
}
/// <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)
{
lock (_lockObject)
{
if (disposing)
{
_componentContext.ComponentRegistry?.Dispose();
}
}
}
private static bool GetWhetherServiceRegistrationMatchesSearch(
IEnumerable<Service> componentRegistrationServices,
Type serviceType,
string contract)
{
foreach (var componentRegistrationService in componentRegistrationServices)
{
if (!(componentRegistrationService is IServiceWithType keyedService))
{
continue;
}
if (keyedService.ServiceType != serviceType)
{
continue;
}
// right type
if (string.IsNullOrEmpty(contract))
{
if (!HasNoContract(componentRegistrationService))
{
continue;
}
// candidate for removal
return true;
}
if (!HasMatchingContract(componentRegistrationService, contract))
{
continue;
}
// candidate for removal
return true;
}
return false;
}
private static bool HasMatchingContract(Service service, string contract)
{
if (!(service is KeyedService keyedService))
{
return false;
}
if (!(keyedService.ServiceKey is string stringServiceKey))
{
return false;
}
return stringServiceKey.Equals(contract, StringComparison.Ordinal);
}
private static bool HasNoContract(Service service)
{
return !(service is KeyedService);
}
private object Resolve(Type serviceType, string contract)
{
object serviceInstance;
if (string.IsNullOrEmpty(contract))
{
_componentContext.TryResolve(serviceType, out serviceInstance);
}
else
{
_componentContext.TryResolveNamed(contract, serviceType, out serviceInstance);
}
return serviceInstance;
}
private void RemoveAndRebuild(
int registrationCount,
IList<IComponentRegistration> registrations,
Func<IComponentRegistration, bool> predicate)
{
var survivingComponents = registrations.Where(predicate).ToArray();
if (survivingComponents.Length == registrationCount)
{
// not removing anything
// drop out
return;
}
RemoveAndRebuild(survivingComponents);
}
private void RemoveAndRebuild(IEnumerable<IComponentRegistration> survivingComponents)
{
var builder = new ContainerBuilder();
foreach (var c in survivingComponents)
{
builder.RegisterComponent(c);
}
foreach (var source in _componentContext.ComponentRegistry.Sources)
{
builder.RegisterSource(source);
}
_componentContext = builder.Build();
}
}
}