-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
EntityFrameworkServiceCollectionExtensions.cs
547 lines (514 loc) · 31.8 KB
/
EntityFrameworkServiceCollectionExtensions.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// 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.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection.Extensions;
// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for setting up Entity Framework related services in an <see cref="IServiceCollection" />.
/// </summary>
public static class EntityFrameworkServiceCollectionExtensions
{
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
/// }
/// </code>
/// </example>
/// <typeparam name="TContext"> The type of context to be registered. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// An optional action to configure the <see cref="DbContextOptions" /> for the context. This provides an
/// alternative to performing configuration of the context by overriding the
/// <see cref="DbContext.OnConfiguring" /> method in your derived context.
/// </para>
/// <para>
/// If an action is supplied here, the <see cref="DbContext.OnConfiguring" /> method will still be run if it has
/// been overridden on the derived context. <see cref="DbContext.OnConfiguring" /> configuration will be applied
/// in addition to configuration performed here.
/// </para>
/// <para>
/// In order for the options to be passed into your context, you need to expose a constructor on your context that takes
/// <see cref="DbContextOptions{TContext}" /> and passes it to the base constructor of <see cref="DbContext" />.
/// </para>
/// </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContext>(
[NotNull] this IServiceCollection serviceCollection,
[CanBeNull] Action<DbContextOptionsBuilder> optionsAction = null,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContext : DbContext
=> AddDbContext<TContext, TContext>(serviceCollection, optionsAction, contextLifetime, optionsLifetime);
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
/// }
/// </code>
/// </example>
/// <typeparam name="TContextService"> The class or interface that will be used to resolve the context from the container. </typeparam>
/// <typeparam name="TContextImplementation"> The concrete implementation type to create. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// An optional action to configure the <see cref="DbContextOptions" /> for the context. This provides an
/// alternative to performing configuration of the context by overriding the
/// <see cref="DbContext.OnConfiguring" /> method in your derived context.
/// </para>
/// <para>
/// If an action is supplied here, the <see cref="DbContext.OnConfiguring" /> method will still be run if it has
/// been overridden on the derived context. <see cref="DbContext.OnConfiguring" /> configuration will be applied
/// in addition to configuration performed here.
/// </para>
/// <para>
/// In order for the options to be passed into your context, you need to expose a constructor on your context that takes
/// <see cref="DbContextOptions{TContext}" /> and passes it to the base constructor of <see cref="DbContext" />.
/// </para>
/// </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
[CanBeNull] Action<DbContextOptionsBuilder> optionsAction = null,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContextImplementation : DbContext, TContextService
=> AddDbContext<TContextService, TContextImplementation>(
serviceCollection,
optionsAction == null
? (Action<IServiceProvider, DbContextOptionsBuilder>)null
: (p, b) => optionsAction.Invoke(b), contextLifetime, optionsLifetime);
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" /> and enables DbContext pooling.
/// Instance pooling can increase throughput in high-scale scenarios such as web servers by re-using
/// DbContext instances, rather than creating new instances for each request.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <typeparam name="TContext"> The type of context to be registered. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// A required action to configure the <see cref="DbContextOptions" /> for the context. When using
/// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" />
/// will not be called.
/// </para>
/// </param>
/// <param name="poolSize">
/// Sets the maximum number of instances retained by the pool.
/// </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContextPool<TContext>(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<DbContextOptionsBuilder> optionsAction,
int poolSize = 128)
where TContext : DbContext
=> AddDbContextPool<TContext, TContext>(serviceCollection, optionsAction, poolSize);
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" /> and enables DbContext pooling.
/// Instance pooling can increase throughput in high-scale scenarios such as web servers by re-using
/// DbContext instances, rather than creating new instances for each request.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <typeparam name="TContextService"> The class or interface that will be used to resolve the context from the container. </typeparam>
/// <typeparam name="TContextImplementation"> The concrete implementation type to create. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// A required action to configure the <see cref="DbContextOptions" /> for the context. When using
/// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" />
/// will not be called.
/// </para>
/// </param>
/// <param name="poolSize">
/// Sets the maximum number of instances retained by the pool.
/// </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContextPool<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<DbContextOptionsBuilder> optionsAction,
int poolSize = 128)
where TContextImplementation : DbContext, TContextService
where TContextService : class
{
Check.NotNull(optionsAction, nameof(optionsAction));
return AddDbContextPool<TContextService, TContextImplementation>(serviceCollection, (_, ob) => optionsAction(ob), poolSize);
}
/// <summary>
/// <para>
/// Registers the given context as a service in the <see cref="IServiceCollection" /> and enables DbContext pooling.
/// Instance pooling can increase throughput in high-scale scenarios such as web servers by re-using
/// DbContext instances, rather than creating new instances for each request.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </para>
/// <para>
/// This overload has an <paramref name="optionsAction" /> that provides the applications <see cref="IServiceProvider" />.
/// This is useful if you want to setup Entity Framework to resolve its internal services from the primary application service
/// provider.
/// By default, we recommend using the other overload, which allows Entity Framework to create and maintain its own
/// <see cref="IServiceProvider" />
/// for internal Entity Framework services.
/// </para>
/// </summary>
/// <typeparam name="TContext"> The type of context to be registered. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// A required action to configure the <see cref="DbContextOptions" /> for the context. When using
/// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" />
/// will not be called.
/// </para>
/// </param>
/// <param name="poolSize">
/// Sets the maximum number of instances retained by the pool.
/// </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContextPool<TContext>(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
int poolSize = 128)
where TContext : DbContext
=> AddDbContextPool<TContext, TContext>(serviceCollection, optionsAction, poolSize);
/// <summary>
/// <para>
/// Registers the given context as a service in the <see cref="IServiceCollection" /> and enables DbContext pooling.
/// Instance pooling can increase throughput in high-scale scenarios such as web servers by re-using
/// DbContext instances, rather than creating new instances for each request.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </para>
/// <para>
/// This overload has an <paramref name="optionsAction" /> that provides the applications <see cref="IServiceProvider" />.
/// This is useful if you want to setup Entity Framework to resolve its internal services from the primary application service
/// provider.
/// By default, we recommend using the other overload, which allows Entity Framework to create and maintain its own
/// <see cref="IServiceProvider" />
/// for internal Entity Framework services.
/// </para>
/// </summary>
/// <typeparam name="TContextService"> The class or interface that will be used to resolve the context from the container. </typeparam>
/// <typeparam name="TContextImplementation"> The concrete implementation type to create. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// A required action to configure the <see cref="DbContextOptions" /> for the context. When using
/// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" />
/// will not be called.
/// </para>
/// </param>
/// <param name="poolSize">
/// Sets the maximum number of instances retained by the pool.
/// </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContextPool<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
[NotNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
int poolSize = 128)
where TContextImplementation : DbContext, TContextService
where TContextService : class
{
Check.NotNull(serviceCollection, nameof(serviceCollection));
Check.NotNull(optionsAction, nameof(optionsAction));
if (poolSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(poolSize), CoreStrings.InvalidPoolSize);
}
CheckContextConstructors<TContextImplementation>();
AddCoreServices<TContextImplementation>(
serviceCollection,
(sp, ob) =>
{
optionsAction(sp, ob);
var extension = (ob.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension())
.WithMaxPoolSize(poolSize);
((IDbContextOptionsBuilderInfrastructure)ob).AddOrUpdateExtension(extension);
},
ServiceLifetime.Singleton);
serviceCollection.TryAddSingleton(
sp => new DbContextPool<TContextImplementation>(
sp.GetService<DbContextOptions<TContextImplementation>>()));
serviceCollection.AddScoped<DbContextPool<TContextImplementation>.Lease>();
serviceCollection.AddScoped(
sp => (TContextService)sp.GetService<DbContextPool<TContextImplementation>.Lease>().Context);
return serviceCollection;
}
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services.AddDbContext<MyContext>(ServiceLifetime.Scoped);
/// }
/// </code>
/// </example>
/// <typeparam name="TContext"> The type of context to be registered. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContext>(
[NotNull] this IServiceCollection serviceCollection,
ServiceLifetime contextLifetime,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContext : DbContext
=> AddDbContext<TContext, TContext>(serviceCollection, contextLifetime, optionsLifetime);
/// <summary>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services.AddDbContext<MyContext>(ServiceLifetime.Scoped);
/// }
/// </code>
/// </example>
/// <typeparam name="TContextService"> The class or interface that will be used to resolve the context from the container. </typeparam>
/// <typeparam name="TContextImplementation"> The concrete implementation type to create. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
ServiceLifetime contextLifetime,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContextImplementation : DbContext, TContextService
where TContextService : class
=> AddDbContext<TContextService, TContextImplementation>(
serviceCollection,
(Action<IServiceProvider, DbContextOptionsBuilder>)null,
contextLifetime,
optionsLifetime);
/// <summary>
/// <para>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </para>
/// <para>
/// This overload has an <paramref name="optionsAction" /> that provides the applications <see cref="IServiceProvider" />.
/// This is useful if you want to setup Entity Framework to resolve its internal services from the primary application service
/// provider.
/// By default, we recommend using the other overload, which allows Entity Framework to create and maintain its own
/// <see cref="IServiceProvider" />
/// for internal Entity Framework services.
/// </para>
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services
/// .AddEntityFrameworkSqlServer()
/// .AddDbContext<MyContext>((serviceProvider, options) =>
/// options.UseSqlServer(connectionString)
/// .UseInternalServiceProvider(serviceProvider));
/// }
/// </code>
/// </example>
/// <typeparam name="TContext"> The type of context to be registered. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// An optional action to configure the <see cref="DbContextOptions" /> for the context. This provides an
/// alternative to performing configuration of the context by overriding the
/// <see cref="DbContext.OnConfiguring" /> method in your derived context.
/// </para>
/// <para>
/// If an action is supplied here, the <see cref="DbContext.OnConfiguring" /> method will still be run if it has
/// been overridden on the derived context. <see cref="DbContext.OnConfiguring" /> configuration will be applied
/// in addition to configuration performed here.
/// </para>
/// <para>
/// In order for the options to be passed into your context, you need to expose a constructor on your context that takes
/// <see cref="DbContextOptions{TContext}" /> and passes it to the base constructor of <see cref="DbContext" />.
/// </para>
/// </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContext>(
[NotNull] this IServiceCollection serviceCollection,
[CanBeNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContext : DbContext
=> AddDbContext<TContext, TContext>(serviceCollection, optionsAction, contextLifetime, optionsLifetime);
/// <summary>
/// <para>
/// Registers the given context as a service in the <see cref="IServiceCollection" />.
/// You use this method when using dependency injection in your application, such as with ASP.NET.
/// For more information on setting up dependency injection, see http://go.microsoft.com/fwlink/?LinkId=526890.
/// </para>
/// <para>
/// This overload has an <paramref name="optionsAction" /> that provides the applications <see cref="IServiceProvider" />.
/// This is useful if you want to setup Entity Framework to resolve its internal services from the primary application service
/// provider.
/// By default, we recommend using the other overload, which allows Entity Framework to create and maintain its own
/// <see cref="IServiceProvider" />
/// for internal Entity Framework services.
/// </para>
/// </summary>
/// <example>
/// <code>
/// public void ConfigureServices(IServiceCollection services)
/// {
/// var connectionString = "connection string to database";
///
/// services
/// .AddEntityFrameworkSqlServer()
/// .AddDbContext<MyContext>((serviceProvider, options) =>
/// options.UseSqlServer(connectionString)
/// .UseInternalServiceProvider(serviceProvider));
/// }
/// </code>
/// </example>
/// <typeparam name="TContextService"> The class or interface that will be used to resolve the context from the container. </typeparam>
/// <typeparam name="TContextImplementation"> The concrete implementation type to create. </typeparam>
/// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param>
/// <param name="optionsAction">
/// <para>
/// An optional action to configure the <see cref="DbContextOptions" /> for the context. This provides an
/// alternative to performing configuration of the context by overriding the
/// <see cref="DbContext.OnConfiguring" /> method in your derived context.
/// </para>
/// <para>
/// If an action is supplied here, the <see cref="DbContext.OnConfiguring" /> method will still be run if it has
/// been overridden on the derived context. <see cref="DbContext.OnConfiguring" /> configuration will be applied
/// in addition to configuration performed here.
/// </para>
/// <para>
/// In order for the options to be passed into your context, you need to expose a constructor on your context that takes
/// <see cref="DbContextOptions{TContext}" /> and passes it to the base constructor of <see cref="DbContext" />.
/// </para>
/// </param>
/// <param name="contextLifetime"> The lifetime with which to register the DbContext service in the container. </param>
/// <param name="optionsLifetime"> The lifetime with which to register the DbContextOptions service in the container. </param>
/// <returns>
/// The same service collection so that multiple calls can be chained.
/// </returns>
public static IServiceCollection AddDbContext<TContextService, TContextImplementation>(
[NotNull] this IServiceCollection serviceCollection,
[CanBeNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
where TContextImplementation : DbContext, TContextService
{
Check.NotNull(serviceCollection, nameof(serviceCollection));
if (contextLifetime == ServiceLifetime.Singleton)
{
optionsLifetime = ServiceLifetime.Singleton;
}
if (optionsAction != null)
{
CheckContextConstructors<TContextImplementation>();
}
AddCoreServices<TContextImplementation>(serviceCollection, optionsAction, optionsLifetime);
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TContextService), typeof(TContextImplementation), contextLifetime));
return serviceCollection;
}
private static void AddCoreServices<TContextImplementation>(
IServiceCollection serviceCollection,
Action<IServiceProvider, DbContextOptionsBuilder> optionsAction,
ServiceLifetime optionsLifetime)
where TContextImplementation : DbContext
{
serviceCollection.TryAdd(
new ServiceDescriptor(
typeof(DbContextOptions<TContextImplementation>),
p => DbContextOptionsFactory<TContextImplementation>(p, optionsAction),
optionsLifetime));
serviceCollection.Add(
new ServiceDescriptor(
typeof(DbContextOptions),
p => p.GetRequiredService<DbContextOptions<TContextImplementation>>(),
optionsLifetime));
}
private static DbContextOptions<TContext> DbContextOptionsFactory<TContext>(
[NotNull] IServiceProvider applicationServiceProvider,
[CanBeNull] Action<IServiceProvider, DbContextOptionsBuilder> optionsAction)
where TContext : DbContext
{
var builder = new DbContextOptionsBuilder<TContext>(
new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>()));
builder.UseApplicationServiceProvider(applicationServiceProvider);
optionsAction?.Invoke(applicationServiceProvider, builder);
return builder.Options;
}
private static void CheckContextConstructors<TContext>()
where TContext : DbContext
{
var declaredConstructors = typeof(TContext).GetTypeInfo().DeclaredConstructors.ToList();
if (declaredConstructors.Count == 1
&& declaredConstructors[0].GetParameters().Length == 0)
{
throw new ArgumentException(CoreStrings.DbContextMissingConstructor(typeof(TContext).ShortDisplayName()));
}
}
}
}