-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathServiceProviderCache.cs
More file actions
203 lines (170 loc) · 8.47 KB
/
ServiceProviderCache.cs
File metadata and controls
203 lines (170 loc) · 8.47 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
namespace Microsoft.EntityFrameworkCore.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class ServiceProviderCache
{
private readonly ConcurrentDictionary<IDbContextOptions, (IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo)>
_configurations = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static ServiceProviderCache Instance { get; } = new();
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual IServiceProvider GetOrAdd(IDbContextOptions options, bool providerRequired)
{
var coreOptionsExtension = options.FindExtension<CoreOptionsExtension>();
var internalServiceProvider = coreOptionsExtension?.InternalServiceProvider;
if (internalServiceProvider != null)
{
ValidateOptions(options);
var optionsInitializer = internalServiceProvider.GetService<ISingletonOptionsInitializer>();
if (optionsInitializer == null)
{
throw new InvalidOperationException(CoreStrings.NoEfServices);
}
if (providerRequired)
{
optionsInitializer.EnsureInitialized(internalServiceProvider, options);
}
return internalServiceProvider;
}
if (coreOptionsExtension?.ServiceProviderCachingEnabled == false)
{
return BuildServiceProvider(options, (_configurations, options)).ServiceProvider;
}
var cacheKey = options;
var extension = options.FindExtension<CoreOptionsExtension>();
if (extension?.ApplicationServiceProvider != null)
{
cacheKey = ((DbContextOptions)options).WithExtension(extension.WithApplicationServiceProvider(null));
}
return _configurations.GetOrAdd(
cacheKey,
static (contextOptions, tuples) => BuildServiceProvider(contextOptions, tuples), (_configurations, options))
.ServiceProvider;
static (IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo) BuildServiceProvider(
IDbContextOptions _,
(ConcurrentDictionary<IDbContextOptions, (IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo)>,
IDbContextOptions) arguments)
{
var (configurations, options) = arguments;
ValidateOptions(options);
var debugInfo = new Dictionary<string, string>();
foreach (var optionsExtension in options.Extensions)
{
optionsExtension.Info.PopulateDebugInfo(debugInfo);
}
debugInfo = debugInfo.OrderBy(_ => debugInfo.Keys).ToDictionary(d => d.Key, v => v.Value);
var services = new ServiceCollection();
var hasProvider = ApplyServices(options, services);
var replacedServices = options.FindExtension<CoreOptionsExtension>()?.ReplacedServices;
if (replacedServices != null)
{
var updatedServices = new ServiceCollection();
foreach (var descriptor in services)
{
if (replacedServices.TryGetValue((descriptor.ServiceType, descriptor.ImplementationType), out var replacementType))
{
((IList<ServiceDescriptor>)updatedServices).Add(
new ServiceDescriptor(descriptor.ServiceType, replacementType, descriptor.Lifetime));
}
else if (replacedServices.TryGetValue((descriptor.ServiceType, null), out replacementType))
{
((IList<ServiceDescriptor>)updatedServices).Add(
new ServiceDescriptor(descriptor.ServiceType, replacementType, descriptor.Lifetime));
}
else
{
((IList<ServiceDescriptor>)updatedServices).Add(descriptor);
}
}
services = updatedServices;
}
var serviceProvider = services.BuildServiceProvider();
if (hasProvider)
{
serviceProvider
.GetRequiredService<ISingletonOptionsInitializer>()
.EnsureInitialized(serviceProvider, options);
}
using (var scope = serviceProvider.CreateScope())
{
var scopedProvider = scope.ServiceProvider;
// If loggingDefinitions is null, then there is no provider yet
var loggingDefinitions = scopedProvider.GetService<LoggingDefinitions>();
if (loggingDefinitions != null)
{
// Because IDbContextOptions cannot yet be resolved from the internal provider
var logger = new DiagnosticsLogger<DbLoggerCategory.Infrastructure>(
ScopedLoggerFactory.Create(scopedProvider, options),
scopedProvider.GetRequiredService<ILoggingOptions>(),
scopedProvider.GetRequiredService<DiagnosticSource>(),
loggingDefinitions,
new NullDbContextLogger());
if (configurations.IsEmpty)
{
logger.ServiceProviderCreated(serviceProvider);
}
else
{
logger.ServiceProviderDebugInfo(
debugInfo,
configurations.Values.Select(v => v.DebugInfo).ToList());
if (configurations.Count >= 20)
{
logger.ManyServiceProvidersCreatedWarning(
configurations.Values.Select(e => e.ServiceProvider).ToList());
}
}
var applicationServiceProvider = options.FindExtension<CoreOptionsExtension>()?.ApplicationServiceProvider;
if (applicationServiceProvider?.GetService<IRegisteredServices>() != null)
{
logger.RedundantAddServicesCallWarning(serviceProvider);
}
}
}
return (serviceProvider, debugInfo);
}
}
private static void ValidateOptions(IDbContextOptions options)
{
foreach (var extension in options.Extensions)
{
extension.Validate(options);
}
}
private static bool ApplyServices(IDbContextOptions options, ServiceCollection services)
{
var coreServicesAdded = false;
foreach (var extension in options.Extensions)
{
extension.ApplyServices(services);
if (extension.Info.IsDatabaseProvider)
{
coreServicesAdded = true;
}
}
if (coreServicesAdded)
{
return true;
}
new EntityFrameworkServicesBuilder(services).TryAddCoreServices();
return false;
}
}