-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
DbContextPool.cs
184 lines (153 loc) · 7.66 KB
/
DbContextPool.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
// 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;
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 DbContextPool<TContext> : IDbContextPool<TContext>, IDisposable, IAsyncDisposable
where TContext : DbContext
{
/// <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 const int DefaultPoolSize = 1024;
private readonly ConcurrentQueue<IDbContextPoolable> _pool = new();
private readonly Func<DbContext> _activator;
private int _maxSize;
private int _count;
/// <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 DbContextPool(DbContextOptions<TContext> options, IServiceProvider? serviceProvider = default)
{
_maxSize = options.FindExtension<CoreOptionsExtension>()?.MaxPoolSize ?? DefaultPoolSize;
if (_maxSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(CoreOptionsExtension.MaxPoolSize), CoreStrings.InvalidPoolSize);
}
options.Freeze();
_activator = CreateActivator(options, serviceProvider);
}
private static Func<DbContext> CreateActivator(DbContextOptions<TContext> options, IServiceProvider? serviceProvider)
{
var constructors = typeof(TContext).GetTypeInfo().DeclaredConstructors
.Where(c => c is { IsStatic: false, IsPublic: true } && c.GetParameters().Length > 0).ToArray();
if (constructors.Length == 1
&& constructors[0].GetParameters() is { } parameters
&& parameters.Any(p => p.ParameterType == typeof(DbContextOptions) || p.ParameterType == typeof(DbContextOptions<TContext>)))
{
if (parameters.Length == 1)
{
return Expression.Lambda<Func<TContext>>(Expression.New(constructors[0], Expression.Constant(options))).Compile();
}
if (serviceProvider is not null)
{
var factory = ActivatorUtilities.CreateFactory<TContext>([typeof(DbContextOptions<TContext>)]);
var activatorParameters = new object[] { options };
return () => factory.Invoke(serviceProvider, activatorParameters);
}
}
throw new InvalidOperationException(CoreStrings.PoolingContextCtorError(typeof(TContext).ShortDisplayName()));
}
/// <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 IDbContextPoolable Rent()
{
if (_pool.TryDequeue(out var context))
{
Interlocked.Decrement(ref _count);
Check.DebugAssert(_count >= 0, $"_count is {_count}");
return context;
}
context = _activator();
context.SnapshotConfiguration();
return context;
}
/// <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 void Return(IDbContextPoolable context)
{
if (Interlocked.Increment(ref _count) <= _maxSize)
{
context.ResetState();
_pool.Enqueue(context);
}
else
{
PooledReturn(context);
}
}
/// <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 async ValueTask ReturnAsync(IDbContextPoolable context, CancellationToken cancellationToken = default)
{
if (Interlocked.Increment(ref _count) <= _maxSize)
{
await context.ResetStateAsync(cancellationToken).ConfigureAwait(false);
_pool.Enqueue(context);
}
else
{
PooledReturn(context);
}
}
private void PooledReturn(IDbContextPoolable context)
{
Interlocked.Decrement(ref _count);
Check.DebugAssert(_maxSize == 0 || _pool.Count <= _maxSize, $"_maxSize is {_maxSize}");
context.ClearLease();
context.Dispose();
}
/// <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 void Dispose()
{
_maxSize = 0;
while (_pool.TryDequeue(out var context))
{
context.ClearLease();
context.Dispose();
}
}
/// <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 async ValueTask DisposeAsync()
{
_maxSize = 0;
while (_pool.TryDequeue(out var context))
{
context.ClearLease();
await context.DisposeAsync().ConfigureAwait(false);
}
}
}