-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
ServiceProviderCache.cs
187 lines (158 loc) · 8.25 KB
/
ServiceProviderCache.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
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<long, (IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo)> _configurations
= new ConcurrentDictionary<long, (IServiceProvider, IDictionary<string, string>)>();
/// <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 ServiceProviderCache();
/// <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([NotNull] 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;
}
(IServiceProvider ServiceProvider, IDictionary<string, string> DebugInfo) BuildServiceProvider()
{
ValidateOptions(options);
var debugInfo = new Dictionary<string, string>();
foreach (var optionsExtension in options.Extensions)
{
optionsExtension.PopulateDebugInfo(debugInfo);
}
debugInfo = debugInfo.OrderBy(v => debugInfo.Keys).ToDictionary(d => d.Key, v => v.Value);
var services = new ServiceCollection();
var hasProvider = ApplyServices(options, services);
var replacedServices = coreOptionsExtension?.ReplacedServices;
if (replacedServices != null)
{
// For replaced services we use the service collection to obtain the lifetime of
// the service to replace. The replaced services are added to a new collection, after
// which provider and core services are applied. This ensures that any patching happens
// to the replaced service.
var updatedServices = new ServiceCollection();
foreach (var descriptor in services)
{
if (replacedServices.TryGetValue(descriptor.ServiceType, out var replacementType))
{
((IList<ServiceDescriptor>) updatedServices).Add(
new ServiceDescriptor(descriptor.ServiceType, replacementType, descriptor.Lifetime));
}
}
ApplyServices(options, updatedServices);
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.GetService<ILoggingOptions>(),
scopedProvider.GetService<DiagnosticSource>(),
loggingDefinitions);
if (_configurations.Count == 0)
{
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());
}
}
}
}
return (serviceProvider, debugInfo);
}
if (coreOptionsExtension?.ServiceProviderCachingEnabled == false)
{
return BuildServiceProvider().ServiceProvider;
}
var key = options.Extensions
.OrderBy(e => e.GetType().Name)
.Aggregate(0L, (t, e) => (t * 397) ^ ((long)e.GetType().GetHashCode() * 397) ^ e.GetServiceProviderHashCode());
return _configurations.GetOrAdd(key, k => BuildServiceProvider()).ServiceProvider;
}
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)
{
if (extension.ApplyServices(services))
{
coreServicesAdded = true;
}
}
if (coreServicesAdded)
{
return true;
}
new EntityFrameworkServicesBuilder(services).TryAddCoreServices();
return false;
}
}
}