-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
DbContextPoolingTest.cs
2186 lines (1741 loc) · 81.6 KB
/
DbContextPoolingTest.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Internal;
// ReSharper disable MethodHasAsyncOverload
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedMember.Local
// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable VirtualMemberCallInConstructor
namespace Microsoft.EntityFrameworkCore;
public class DbContextPoolingTest : IClassFixture<NorthwindQuerySqlServerFixture<NoopModelCustomizer>>
{
private static DbContextOptionsBuilder<TContext> ConfigureOptions<TContext>(DbContextOptionsBuilder<TContext> optionsBuilder)
where TContext : DbContext
=> optionsBuilder
.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString)
.EnableServiceProviderCaching(false);
private static DbContextOptionsBuilder ConfigureOptions(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString)
.EnableServiceProviderCaching(false);
private static IServiceProvider BuildServiceProvider<TContextService, TContext>(Action<DbContextOptionsBuilder> optionsAction = null)
where TContextService : class
where TContext : DbContext, TContextService
=> new ServiceCollection()
.AddDbContextPool<TContextService, TContext>(
ob =>
{
var builder = ConfigureOptions(ob);
if (optionsAction != null)
{
optionsAction(builder);
}
})
.AddDbContextPool<ISecondContext, SecondContext>(
ob =>
{
var builder = ConfigureOptions(ob);
if (optionsAction != null)
{
optionsAction(builder);
}
})
.BuildServiceProvider(validateScopes: true);
private static IServiceProvider BuildServiceProvider<TContext>(Action<DbContextOptionsBuilder> optionsAction = null)
where TContext : DbContext
=> new ServiceCollection()
.AddDbContextPool<TContext>(
ob =>
{
var builder = ConfigureOptions(ob);
if (optionsAction != null)
{
optionsAction(builder);
}
})
.AddDbContextPool<SecondContext>(
ob =>
{
var builder = ConfigureOptions(ob);
if (optionsAction != null)
{
optionsAction(builder);
}
})
.BuildServiceProvider(validateScopes: true);
private static IServiceProvider BuildServiceProviderWithFactory<TContext>()
where TContext : DbContext
=> new ServiceCollection()
.AddPooledDbContextFactory<TContext>(ob => ConfigureOptions(ob))
.AddDbContextPool<SecondContext>(ob => ConfigureOptions(ob))
.BuildServiceProvider(validateScopes: true);
private static IServiceProvider BuildServiceProvider<TContextService, TContext>(int poolSize)
where TContextService : class
where TContext : DbContext, TContextService
=> new ServiceCollection()
.AddDbContextPool<TContextService, TContext>(ob => ConfigureOptions(ob), poolSize)
.AddDbContextPool<ISecondContext, SecondContext>(ob => ConfigureOptions(ob), poolSize)
.BuildServiceProvider(validateScopes: true);
private static IServiceProvider BuildServiceProvider<TContext>(int poolSize)
where TContext : DbContext
=> new ServiceCollection()
.AddDbContextPool<TContext>(ob => ConfigureOptions(ob), poolSize)
.AddDbContextPool<SecondContext>(ob => ConfigureOptions(ob), poolSize)
.BuildServiceProvider(validateScopes: true);
private static IServiceProvider BuildServiceProviderWithFactory<TContext>(int poolSize)
where TContext : DbContext
=> new ServiceCollection()
.AddPooledDbContextFactory<TContext>(ob => ConfigureOptions(ob), poolSize)
.AddDbContextPool<SecondContext>(ob => ConfigureOptions(ob), poolSize)
.BuildServiceProvider(validateScopes: true);
private static IDbContextFactory<TContext> BuildFactory<TContext>(bool withDependencyInjection)
where TContext : DbContext
=> withDependencyInjection
? BuildServiceProviderWithFactory<TContext>().GetService<IDbContextFactory<TContext>>()
: new PooledDbContextFactory<TContext>(ConfigureOptions(new DbContextOptionsBuilder<TContext>()).Options);
private static IDbContextFactory<TContext> BuildFactory<TContext>(bool withDependencyInjection, int poolSize)
where TContext : DbContext
=> withDependencyInjection
? BuildServiceProviderWithFactory<TContext>(poolSize).GetService<IDbContextFactory<TContext>>()
: new PooledDbContextFactory<TContext>(ConfigureOptions(new DbContextOptionsBuilder<TContext>()).Options, poolSize);
private interface IPooledContext
{
}
private class DefaultOptionsPooledContext : DbContext
{
public DefaultOptionsPooledContext(DbContextOptions options)
: base(options)
{
}
}
private class PooledContext : DbContext, IPooledContext
{
public static int DisposedCount;
public static int InstanceCount;
public static bool ModifyOptions;
public PooledContext(DbContextOptions options)
: base(options)
{
Interlocked.Increment(ref InstanceCount);
ChangeTracker.AutoDetectChangesEnabled = false;
ChangeTracker.LazyLoadingEnabled = false;
Database.AutoTransactionBehavior = AutoTransactionBehavior.Never;
Database.AutoSavepointsEnabled = false;
ChangeTracker.CascadeDeleteTiming = CascadeTiming.Never;
ChangeTracker.DeleteOrphansTiming = CascadeTiming.Never;
SavingChanges += (sender, args) => { };
SavedChanges += (sender, args) => { };
SaveChangesFailed += (sender, args) => { };
ChangeTracker.Tracking += (sender, args) => { };
ChangeTracker.Tracked += (sender, args) => { };
ChangeTracker.StateChanging += (sender, args) => { };
ChangeTracker.StateChanged += (sender, args) => { };
ChangeTracker.DetectingAllChanges += (sender, args) => { };
ChangeTracker.DetectedAllChanges += (sender, args) => { };
ChangeTracker.DetectingEntityChanges += (sender, args) => { };
ChangeTracker.DetectedEntityChanges += (sender, args) => { };
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (ModifyOptions)
{
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}
}
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customers");
modelBuilder.Entity<Order>().ToTable("Orders");
}
public override void Dispose()
{
base.Dispose();
Interlocked.Increment(ref DisposedCount);
}
}
private class PooledContextWithOverrides : DbContext, IPooledContext
{
public PooledContextWithOverrides(DbContextOptions options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customers");
modelBuilder.Entity<Order>().ToTable("Orders");
}
}
public class Customer
{
public string CustomerId { get; set; }
public string CompanyName { get; set; }
public ILazyLoader LazyLoader { get; set; }
public ObservableCollection<Order> Orders { get; } = new();
}
public class Order
{
public int OrderId { get; set; }
public ILazyLoader LazyLoader { get; set; }
public string CustomerId { get; set; }
public Customer Customer { get; set; }
}
private interface ISecondContext
{
}
private class SecondContext : DbContext, ISecondContext
{
public DbSet<Blog> Blogs { get; set; }
public SecondContext(DbContextOptions options)
: base(options)
{
}
public class Blog
{
public int Id { get; set; }
}
}
[ConditionalFact]
public void Invalid_pool_size()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildServiceProvider<PooledContext>(poolSize: 0));
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildServiceProvider<PooledContext>(poolSize: -1));
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildServiceProvider<IPooledContext, PooledContext>(poolSize: 0));
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildServiceProvider<IPooledContext, PooledContext>(poolSize: -1));
}
[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public void Invalid_pool_size_with_factory(bool withDependencyInjection)
{
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildFactory<PooledContext>(withDependencyInjection, poolSize: 0));
Assert.Throws<ArgumentOutOfRangeException>(
() => BuildFactory<PooledContext>(withDependencyInjection, poolSize: -1));
}
[ConditionalFact]
public void Validate_pool_size()
{
var serviceProvider = BuildServiceProvider<PooledContext>(poolSize: 64);
using var scope = serviceProvider.CreateScope();
Assert.Equal(
64,
scope.ServiceProvider
.GetRequiredService<PooledContext>()
.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalFact]
public void Validate_pool_size_with_service_interface()
{
var serviceProvider = BuildServiceProvider<IPooledContext, PooledContext>(poolSize: 64);
using var scope = serviceProvider.CreateScope();
Assert.Equal(
64,
((DbContext)scope.ServiceProvider
.GetRequiredService<IPooledContext>())
.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalFact]
public void Validate_pool_size_with_factory()
{
var serviceProvider = BuildServiceProviderWithFactory<PooledContext>(poolSize: 64);
using var context = serviceProvider.GetRequiredService<IDbContextFactory<PooledContext>>().CreateDbContext();
Assert.Equal(
64,
context.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public void Validate_pool_size_behavior_with_factory(bool withDependencyInjection)
{
var factory = BuildFactory<PooledContext>(withDependencyInjection, poolSize: 1);
var (ctx1, ctx2) = (factory.CreateDbContext(), factory.CreateDbContext());
ctx1.Dispose();
ctx2.Dispose();
using var ctx3 = factory.CreateDbContext();
using var ctx4 = factory.CreateDbContext();
Assert.Same(ctx1, ctx3);
Assert.NotSame(ctx2, ctx4);
}
[ConditionalFact]
public void Validate_pool_size_default()
{
var serviceProvider = BuildServiceProvider<PooledContext>();
using var scope = serviceProvider.CreateScope();
Assert.Equal(
1024,
scope.ServiceProvider
.GetRequiredService<PooledContext>()
.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalFact]
public void Validate_pool_size_with_service_interface_default()
{
var serviceProvider = BuildServiceProvider<IPooledContext, PooledContext>();
using var scope = serviceProvider.CreateScope();
Assert.Equal(
1024,
((DbContext)scope.ServiceProvider
.GetRequiredService<IPooledContext>())
.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalFact]
public void Pool_can_get_context_by_concrete_type_even_when_service_interface_is_used()
{
var serviceProvider = BuildServiceProvider<IPooledContext, PooledContext>();
using var scope = serviceProvider.CreateScope();
Assert.Same(
scope.ServiceProvider.GetRequiredService<IPooledContext>(),
scope.ServiceProvider.GetRequiredService<PooledContext>());
}
[ConditionalFact]
public void Validate_pool_size_with_factory_default()
{
var serviceProvider = BuildServiceProviderWithFactory<PooledContext>();
using var context = serviceProvider.GetRequiredService<IDbContextFactory<PooledContext>>().CreateDbContext();
Assert.Equal(
1024,
context.GetService<IDbContextOptions>()
.FindExtension<CoreOptionsExtension>()!.MaxPoolSize);
}
[ConditionalTheory]
[InlineData(true)]
[InlineData(false)]
public void Options_modified_in_on_configuring(bool useInterface)
{
var serviceProvider = useInterface
? BuildServiceProvider<IPooledContext, PooledContext>()
: BuildServiceProvider<PooledContext>();
var scopedProvider = serviceProvider.CreateScope().ServiceProvider;
PooledContext.ModifyOptions = true;
try
{
Assert.Throws<InvalidOperationException>(
() => useInterface
? scopedProvider.GetService<IPooledContext>()
: scopedProvider.GetService<PooledContext>());
}
finally
{
PooledContext.ModifyOptions = false;
}
}
[ConditionalFact]
public void Options_modified_in_on_configuring_with_factory()
{
var serviceProvider = BuildServiceProviderWithFactory<PooledContext>();
var scopedProvider = serviceProvider.CreateScope().ServiceProvider;
PooledContext.ModifyOptions = true;
try
{
var factory = scopedProvider.GetService<IDbContextFactory<PooledContext>>();
Assert.Throws<InvalidOperationException>(() => factory!.CreateDbContext());
}
finally
{
PooledContext.ModifyOptions = false;
}
}
private class BadCtorContext : DbContext
{
}
[ConditionalFact]
public void Throws_when_used_with_parameterless_constructor_context()
{
var serviceCollection = new ServiceCollection();
Assert.Equal(
CoreStrings.DbContextMissingConstructor(nameof(BadCtorContext)),
Assert.Throws<ArgumentException>(
() => serviceCollection.AddDbContextPool<BadCtorContext>(
_ => { })).Message);
Assert.Equal(
CoreStrings.DbContextMissingConstructor(nameof(BadCtorContext)),
Assert.Throws<ArgumentException>(
() => serviceCollection.AddDbContextPool<BadCtorContext>(
(_, __) => { })).Message);
Assert.Equal(
CoreStrings.DbContextMissingConstructor(nameof(BadCtorContext)),
Assert.Throws<ArgumentException>(
() => serviceCollection.AddPooledDbContextFactory<BadCtorContext>(
(_, __) => { })).Message);
}
[ConditionalFact]
public void Throws_when_pooled_context_constructor_has_second_parameter_that_cannot_be_resolved_from_service_provider()
{
var serviceProvider
= new ServiceCollection().AddDbContextPool<TwoParameterConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
Assert.Throws<InvalidOperationException>(() => scope.ServiceProvider.GetService<TwoParameterConstructorContext>());
}
private class TwoParameterConstructorContext : DbContext
{
public string StringParameter { get; }
public TwoParameterConstructorContext(DbContextOptions options, string x)
: base(options)
{
StringParameter = x;
}
}
[ConditionalFact]
public void Throws_when_pooled_context_constructor_has_single_parameter_that_cannot_be_resolved_from_service_provider()
{
var serviceProvider
= new ServiceCollection().AddDbContextPool<WrongParameterConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
Assert.Throws<InvalidOperationException>(() => scope.ServiceProvider.GetService<WrongParameterConstructorContext>());
}
private class WrongParameterConstructorContext : DbContext
{
public WrongParameterConstructorContext(string x)
: base(new DbContextOptions<WrongParameterConstructorContext>())
{
}
}
[ConditionalFact]
public void Throws_when_pooled_context_constructor_has_scoped_service()
{
var serviceProvider
= new ServiceCollection()
.AddDbContextPool<TwoParameterConstructorContext>(_ => { })
.AddScoped(sp => "string")
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
Assert.Throws<InvalidOperationException>(() => scope.ServiceProvider.GetService<TwoParameterConstructorContext>());
}
[ConditionalFact]
public void Does_not_throw_when_pooled_context_constructor_has_singleton_service()
{
var serviceProvider
= new ServiceCollection()
.AddDbContextPool<TwoParameterConstructorContext>(_ => { })
.AddSingleton("string")
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetService<TwoParameterConstructorContext>();
Assert.Equal("string", context.StringParameter);
}
[ConditionalFact]
public void Does_not_throw_when_parameterless_and_correct_constructor()
{
var serviceProvider
= new ServiceCollection().AddDbContextPool<WithParameterlessConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<WithParameterlessConstructorContext>();
Assert.Equal("Options", context.ConstructorUsed);
}
[ConditionalFact]
public void Does_not_throw_when_parameterless_and_correct_constructor_using_factory_pool()
{
var serviceProvider
= new ServiceCollection().AddPooledDbContextFactory<WithParameterlessConstructorContext>(_ => { })
.BuildServiceProvider(validateScopes: true);
using var scope = serviceProvider.CreateScope();
var factory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<WithParameterlessConstructorContext>>();
using var context = factory.CreateDbContext();
Assert.Equal("Options", context.ConstructorUsed);
}
private class WithParameterlessConstructorContext : DbContext
{
public string ConstructorUsed { get; }
public WithParameterlessConstructorContext()
{
ConstructorUsed = "Parameterless";
}
public WithParameterlessConstructorContext(DbContextOptions<WithParameterlessConstructorContext> options)
: base(options)
{
ConstructorUsed = "Options";
}
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task Can_pool_non_derived_context(bool useFactory, bool async)
{
var serviceProvider = useFactory
? BuildServiceProviderWithFactory<DbContext>()
: BuildServiceProvider<DbContext>();
var serviceScope1 = serviceProvider.CreateScope();
var context1 = await GetContextAsync(serviceScope1);
var serviceScope2 = serviceProvider.CreateScope();
var context2 = await GetContextAsync(serviceScope2);
Assert.NotSame(context1, context2);
var id1 = context1.ContextId;
var id2 = context2.ContextId;
Assert.NotEqual(default, id1.InstanceId);
Assert.NotEqual(id1, id2);
Assert.NotEqual(id1.InstanceId, id2.InstanceId);
Assert.Equal(1, id1.Lease);
Assert.Equal(1, id2.Lease);
if (useFactory)
{
await Dispose(context1, async);
}
await Dispose(serviceScope1, async);
await Dispose(serviceScope2, async);
if (useFactory)
{
await Dispose(context2, async);
}
var id1d = context1.ContextId;
var id2d = context2.ContextId;
Assert.Equal(id1, id1d);
Assert.Equal(id1.InstanceId, id1d.InstanceId);
Assert.Equal(1, id1d.Lease);
Assert.Equal(1, id2d.Lease);
var serviceScope3 = serviceProvider.CreateScope();
var context3 = await GetContextAsync(serviceScope3);
var id1r = context3.ContextId;
Assert.Same(context1, context3);
Assert.Equal(id1.InstanceId, id1r.InstanceId);
Assert.NotEqual(default, id1r.InstanceId);
Assert.NotEqual(id1, id1r);
Assert.Equal(2, id1r.Lease);
var serviceScope4 = serviceProvider.CreateScope();
var context4 = await GetContextAsync(serviceScope4);
var id2r = context4.ContextId;
Assert.Same(context2, context4);
Assert.Equal(id2.InstanceId, id2r.InstanceId);
Assert.NotEqual(default, id2r.InstanceId);
Assert.NotEqual(id2, id2r);
Assert.Equal(2, id2r.Lease);
async Task<DbContext> GetContextAsync(IServiceScope serviceScope)
=> useFactory
? async
? await serviceScope.ServiceProvider.GetService<IDbContextFactory<DbContext>>()!.CreateDbContextAsync()
: serviceScope.ServiceProvider.GetService<IDbContextFactory<DbContext>>()!.CreateDbContext()
: serviceScope.ServiceProvider.GetService<DbContext>();
}
[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public async Task ContextIds_make_sense_when_not_pooling(bool async)
{
var serviceProvider = new ServiceCollection()
.AddDbContext<DbContext>(
ob
=> ob.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString)
.EnableServiceProviderCaching(false))
.BuildServiceProvider(validateScopes: true);
var serviceScope1 = serviceProvider.CreateScope();
var context1 = serviceScope1.ServiceProvider.GetService<DbContext>();
var serviceScope2 = serviceProvider.CreateScope();
var context2 = serviceScope2.ServiceProvider.GetService<DbContext>();
Assert.NotSame(context1, context2);
var id1 = context1!.ContextId;
var id2 = context2!.ContextId;
Assert.NotEqual(default, id1.InstanceId);
Assert.NotEqual(default, id2.InstanceId);
Assert.NotEqual(id1, id2);
Assert.Equal(0, id1.Lease);
Assert.Equal(0, id2.Lease);
await Dispose(serviceScope1, async);
await Dispose(serviceScope2, async);
var id1d = context1.ContextId;
var id2d = context2.ContextId;
Assert.Equal(id1.InstanceId, id1d.InstanceId);
Assert.Equal(id2.InstanceId, id2d.InstanceId);
Assert.Equal(0, id1d.Lease);
Assert.Equal(0, id2d.Lease);
var serviceScope3 = serviceProvider.CreateScope();
var context3 = serviceScope3.ServiceProvider.GetService<DbContext>();
var id1r = context3.ContextId;
Assert.NotSame(context1, context3);
Assert.NotEqual(default, id1r.InstanceId);
Assert.NotEqual(id1.InstanceId, id1r.InstanceId);
Assert.NotEqual(id1, id1r);
Assert.Equal(0, id1r.Lease);
var serviceScope4 = serviceProvider.CreateScope();
var context4 = serviceScope4.ServiceProvider.GetService<DbContext>();
var id2r = context4.ContextId;
Assert.NotSame(context2, context4);
Assert.NotEqual(default, id2r.InstanceId);
Assert.NotEqual(id2.InstanceId, id2r.InstanceId);
Assert.NotEqual(id2, id2r);
Assert.Equal(0, id2r.Lease);
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task Contexts_are_pooled(bool useInterface, bool async)
{
var serviceProvider = useInterface
? BuildServiceProvider<IPooledContext, PooledContext>()
: BuildServiceProvider<PooledContext>();
var serviceScope1 = serviceProvider.CreateScope();
var scopedProvider1 = serviceScope1.ServiceProvider;
var context1 = useInterface
? scopedProvider1.GetService<IPooledContext>()
: scopedProvider1.GetService<PooledContext>();
var secondContext1 = useInterface
? scopedProvider1.GetService<ISecondContext>()
: scopedProvider1.GetService<SecondContext>();
var serviceScope2 = serviceProvider.CreateScope();
var scopedProvider2 = serviceScope2.ServiceProvider;
var context2 = useInterface
? scopedProvider2.GetService<IPooledContext>()
: scopedProvider2.GetService<PooledContext>();
var secondContext2 = useInterface
? scopedProvider2.GetService<ISecondContext>()
: scopedProvider2.GetService<SecondContext>();
Assert.NotSame(context1, context2);
Assert.NotSame(secondContext1, secondContext2);
await Dispose(serviceScope1, async);
await Dispose(serviceScope2, async);
var serviceScope3 = serviceProvider.CreateScope();
var scopedProvider3 = serviceScope3.ServiceProvider;
var context3 = useInterface
? scopedProvider3.GetService<IPooledContext>()
: scopedProvider3.GetService<PooledContext>();
var secondContext3 = useInterface
? scopedProvider3.GetService<ISecondContext>()
: scopedProvider3.GetService<SecondContext>();
Assert.Same(context1, context3);
Assert.Same(secondContext1, secondContext3);
var serviceScope4 = serviceProvider.CreateScope();
var scopedProvider4 = serviceScope4.ServiceProvider;
var context4 = useInterface
? scopedProvider4.GetService<IPooledContext>()
: scopedProvider4.GetService<PooledContext>();
var secondContext4 = useInterface
? scopedProvider4.GetService<ISecondContext>()
: scopedProvider4.GetService<SecondContext>();
Assert.Same(context2, context4);
Assert.Same(secondContext2, secondContext4);
await Dispose(serviceScope3, async);
await Dispose(serviceScope4, async);
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task Contexts_are_pooled_with_factory(bool async, bool withDependencyInjection)
{
var factory = BuildFactory<PooledContext>(withDependencyInjection);
var context1 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var secondContext1 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var context2 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var secondContext2 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
Assert.NotSame(context1, context2);
Assert.NotSame(secondContext1, secondContext2);
await Dispose(context1, async);
await Dispose(secondContext1, async);
await Dispose(context2, async);
await Dispose(secondContext2, async);
var context3 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var secondContext3 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
Assert.Same(context1, context3);
Assert.Same(secondContext1, secondContext3);
var context4 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var secondContext4 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
Assert.Same(context2, context4);
Assert.Same(secondContext2, secondContext4);
await Dispose(context1, async);
await Dispose(secondContext1, async);
await Dispose(context2, async);
await Dispose(secondContext2, async);
}
[ConditionalTheory]
[InlineData(false, false, null)]
[InlineData(true, false, null)]
[InlineData(false, true, null)]
[InlineData(true, true, null)]
[InlineData(false, false, QueryTrackingBehavior.TrackAll)]
[InlineData(true, false, QueryTrackingBehavior.TrackAll)]
[InlineData(false, true, QueryTrackingBehavior.TrackAll)]
[InlineData(true, true, QueryTrackingBehavior.TrackAll)]
[InlineData(false, false, QueryTrackingBehavior.NoTracking)]
[InlineData(true, false, QueryTrackingBehavior.NoTracking)]
[InlineData(false, true, QueryTrackingBehavior.NoTracking)]
[InlineData(true, true, QueryTrackingBehavior.NoTracking)]
[InlineData(false, false, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
[InlineData(true, false, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
[InlineData(false, true, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
[InlineData(true, true, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
public async Task Context_configuration_is_reset(bool useInterface, bool async, QueryTrackingBehavior? queryTrackingBehavior)
{
var serviceProvider = useInterface
? BuildServiceProvider<IPooledContext, PooledContext>(b => UseQueryTrackingBehavior(b, queryTrackingBehavior))
: BuildServiceProvider<PooledContext>(b => UseQueryTrackingBehavior(b, queryTrackingBehavior));
var serviceScope = serviceProvider.CreateScope();
var scopedProvider = serviceScope.ServiceProvider;
var context1 = useInterface
? (PooledContext)scopedProvider.GetService<IPooledContext>()
: scopedProvider.GetService<PooledContext>();
Assert.Null(context1!.Database.GetCommandTimeout());
var set = context1.Customers;
var localView = set.Local;
localView.PropertyChanged += LocalView_OnPropertyChanged;
localView.PropertyChanging += LocalView_OnPropertyChanging;
localView.CollectionChanged += LocalView_OnCollectionChanged;
var customer1 = new Customer { CustomerId = "C" };
context1.Customers.Attach(customer1);
Assert.Equal(1, localView.Count);
Assert.Same(customer1, localView.ToBindingList().Single());
Assert.Same(customer1, localView.ToObservableCollection().Single());
Assert.True(_localView_OnPropertyChanging);
Assert.True(_localView_OnPropertyChanged);
Assert.True(_localView_OnCollectionChanged);
context1.ChangeTracker.AutoDetectChangesEnabled = true;
context1.ChangeTracker.LazyLoadingEnabled = true;
context1.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
context1.ChangeTracker.CascadeDeleteTiming = CascadeTiming.Immediate;
context1.ChangeTracker.DeleteOrphansTiming = CascadeTiming.Immediate;
context1.Database.AutoTransactionBehavior = AutoTransactionBehavior.WhenNeeded;
context1.Database.AutoSavepointsEnabled = true;
context1.Database.SetCommandTimeout(1);
context1.ChangeTracker.Tracking += ChangeTracker_OnTracking;
context1.ChangeTracker.Tracked += ChangeTracker_OnTracked;
context1.ChangeTracker.StateChanging += ChangeTracker_OnStateChanging;
context1.ChangeTracker.StateChanged += ChangeTracker_OnStateChanged;
context1.ChangeTracker.DetectingAllChanges += ChangeTracker_OnDetectingAllChanges;
context1.ChangeTracker.DetectedAllChanges += ChangeTracker_OnDetectedAllChanges;
context1.ChangeTracker.DetectingEntityChanges += ChangeTracker_OnDetectingEntityChanges;
context1.ChangeTracker.DetectedEntityChanges += ChangeTracker_OnDetectedEntityChanges;
context1.SavingChanges += Context_OnSavingChanges;
context1.SavedChanges += Context_OnSavedChanges;
context1.SaveChangesFailed += Context_OnSaveChangesFailed;
_localView_OnPropertyChanging = false;
_localView_OnPropertyChanged = false;
_localView_OnCollectionChanged = false;
await Dispose(serviceScope, async);
serviceScope = serviceProvider.CreateScope();
scopedProvider = serviceScope.ServiceProvider;
var context2 = useInterface
? (PooledContext)scopedProvider.GetService<IPooledContext>()
: scopedProvider.GetService<PooledContext>();
Assert.Same(context1, context2);
Assert.False(context2!.ChangeTracker.AutoDetectChangesEnabled);
Assert.False(context2.ChangeTracker.LazyLoadingEnabled);
Assert.Equal(queryTrackingBehavior ?? QueryTrackingBehavior.TrackAll, context2.ChangeTracker.QueryTrackingBehavior);
Assert.Equal(CascadeTiming.Never, context2.ChangeTracker.CascadeDeleteTiming);
Assert.Equal(CascadeTiming.Never, context2.ChangeTracker.DeleteOrphansTiming);
Assert.Equal(AutoTransactionBehavior.Never, context2.Database.AutoTransactionBehavior);
Assert.False(context2.Database.AutoSavepointsEnabled);
Assert.Null(context1.Database.GetCommandTimeout());
Assert.Empty(localView);
Assert.Empty(localView.ToBindingList());
Assert.Empty(localView.ToObservableCollection());
var customer2 = new Customer { CustomerId = "C" };
context2.Customers.Attach(customer2).State = EntityState.Modified;
context2.Customers.Attach(customer2).State = EntityState.Unchanged;
Assert.False(_changeTracker_OnTracking);
Assert.False(_changeTracker_OnTracked);
Assert.False(_changeTracker_OnStateChanging);
Assert.False(_changeTracker_OnStateChanged);
context2.SaveChanges();
Assert.False(_changeTracker_OnDetectingAllChanges);
Assert.False(_changeTracker_OnDetectedAllChanges);
Assert.False(_changeTracker_OnDetectingEntityChanges);
Assert.False(_changeTracker_OnDetectedEntityChanges);
Assert.False(_context_OnSavedChanges);
Assert.False(_context_OnSavingChanges);
Assert.False(_context_OnSaveChangesFailed);
Assert.Same(set, context2!.Customers);
Assert.Same(localView, context2!.Customers.Local);
Assert.Equal(1, localView.Count);
Assert.Same(customer2, localView.ToBindingList().Single());
Assert.Same(customer2, localView.ToObservableCollection().Single());
Assert.False(_localView_OnPropertyChanging);
Assert.False(_localView_OnPropertyChanged);
Assert.False(_localView_OnCollectionChanged);
}
[ConditionalTheory]
[InlineData(false, null)]
[InlineData(true, null)]
[InlineData(false, QueryTrackingBehavior.TrackAll)]
[InlineData(true, QueryTrackingBehavior.TrackAll)]
[InlineData(false, QueryTrackingBehavior.NoTracking)]
[InlineData(true, QueryTrackingBehavior.NoTracking)]
[InlineData(false, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
[InlineData(true, QueryTrackingBehavior.NoTrackingWithIdentityResolution)]
public async Task Uninitialized_context_configuration_is_reset_properly(bool async, QueryTrackingBehavior? queryTrackingBehavior)
{
var serviceProvider = BuildServiceProvider<SecondContext>(b => UseQueryTrackingBehavior(b, queryTrackingBehavior));
var serviceScope = serviceProvider.CreateScope();
var ctx = serviceScope.ServiceProvider.GetRequiredService<SecondContext>();
await Dispose(ctx, async);
await Dispose(serviceScope, async);
serviceScope = serviceProvider.CreateScope();
var ctx2 = serviceScope.ServiceProvider.GetRequiredService<SecondContext>();
Assert.Same(ctx, ctx2);
ctx2.Blogs.Add(new SecondContext.Blog());
await Dispose(ctx2, async);
await Dispose(serviceScope, async);
serviceScope = serviceProvider.CreateScope();
var ctx3 = serviceScope.ServiceProvider.GetRequiredService<SecondContext>();
Assert.Same(ctx, ctx3);
Assert.Empty(ctx3.ChangeTracker.Entries());
await Dispose(ctx2, async);
await Dispose(serviceScope, async);
}
[ConditionalTheory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task Context_configuration_is_reset_with_factory(bool async, bool withDependencyInjection)
{
var factory = BuildFactory<PooledContext>(withDependencyInjection);
var context1 = async ? await factory.CreateDbContextAsync() : factory.CreateDbContext();
var set = context1.Customers;
var localView = set.Local;
localView.PropertyChanged += LocalView_OnPropertyChanged;
localView.PropertyChanging += LocalView_OnPropertyChanging;