-
-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathPropertyInjector.cs
More file actions
679 lines (592 loc) · 26.6 KB
/
Copy pathPropertyInjector.cs
File metadata and controls
679 lines (592 loc) · 26.6 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
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
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using TUnit.Core;
using TUnit.Core.Helpers;
using TUnit.Core.Interfaces;
using TUnit.Core.Interfaces.SourceGenerator;
using TUnit.Core.PropertyInjection;
using TUnit.Core.PropertyInjection.Initialization;
namespace TUnit.Engine.Services;
/// <summary>
/// Pure property injection service.
/// Follows Single Responsibility Principle - only injects property values, doesn't initialize objects.
/// Uses Lazy initialization to break circular dependencies without manual Initialize() calls.
/// </summary>
/// <remarks>
/// Depends on <see cref="IInitializationCallback"/> rather than a concrete service,
/// enabling testability and following Dependency Inversion Principle.
/// </remarks>
internal sealed class PropertyInjector
{
private readonly Lazy<IInitializationCallback> _initializationCallback;
private readonly string _testSessionId;
// Object pool for visited dictionaries to reduce allocations
private static readonly ConcurrentBag<ConcurrentDictionary<object, byte>> _visitedObjectsPool = new();
// Cache for PropertyInfo lookups by (ContainingType, PropertyName) to avoid repeated reflection
private static readonly ConcurrentDictionary<(Type, string), PropertyInfo?> _propertyInfoCache = new();
public PropertyInjector(Lazy<IInitializationCallback> initializationCallback, string testSessionId)
{
_initializationCallback = initializationCallback;
_testSessionId = testSessionId;
}
/// <summary>
/// Resolves and caches property values for a test class type WITHOUT setting them on an instance.
/// Used during registration to create shared objects early and enable proper reference counting.
/// </summary>
public Task ResolveAndCachePropertiesAsync(
Type testClassType,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
CancellationToken cancellationToken = default)
{
// Skip property resolution if this test is reusing the discovery instance (already initialized)
if (testContext.IsDiscoveryInstanceReused)
{
return Task.CompletedTask;
}
var plan = PropertyInjectionCache.GetOrCreatePlan(testClassType);
if (!plan.HasProperties)
{
return Task.CompletedTask;
}
return ResolveAndCachePropertiesCoreAsync(objectBag, methodMetadata, events, testContext, plan, cancellationToken);
}
private Task ResolveAndCachePropertiesCoreAsync(
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
PropertyInjectionPlan plan,
CancellationToken cancellationToken)
{
if (plan.SourceGeneratedProperties.Length > 0)
{
return ResolveAndCacheSourceGeneratedPropertiesAsync(
plan.SourceGeneratedProperties, objectBag, methodMetadata, events, testContext, cancellationToken);
}
if (plan.ReflectionProperties.Length > 0)
{
return ResolveAndCacheReflectionPropertiesAsync(
plan.ReflectionProperties, objectBag, methodMetadata, events, testContext, cancellationToken);
}
return Task.CompletedTask;
}
/// <summary>
/// Injects properties into an object and recursively into nested objects.
/// </summary>
public async Task InjectPropertiesAsync(
object instance,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
CancellationToken cancellationToken = default)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
if (objectBag == null)
{
throw new ArgumentNullException(nameof(objectBag));
}
if (events == null)
{
throw new ArgumentNullException(nameof(events));
}
var visitedObjects = RentVisitedDictionary();
try
{
await InjectPropertiesRecursiveAsync(instance, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
finally
{
ReturnVisitedDictionary(visitedObjects);
}
}
/// <summary>
/// Injects properties into multiple argument objects in parallel.
/// </summary>
public async Task InjectPropertiesIntoArgumentsAsync(
object?[] arguments,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata methodMetadata,
TestContextEvents events,
CancellationToken cancellationToken = default)
{
if (arguments.Length == 0)
{
return;
}
// Build list of injectable args without LINQ
var injectableArgs = new List<object>(arguments.Length);
for (var i = 0; i < arguments.Length; i++)
{
var arg = arguments[i];
if (arg != null && PropertyInjectionCache.HasInjectableProperties(arg.GetType()))
{
injectableArgs.Add(arg);
}
}
if (injectableArgs.Count == 0)
{
return;
}
// Build task list without LINQ Select
var tasks = new List<Task>(injectableArgs.Count);
for (var i = 0; i < injectableArgs.Count; i++)
{
tasks.Add(InjectPropertiesAsync(injectableArgs[i], objectBag, methodMetadata, events, cancellationToken));
}
await Task.WhenAll(tasks);
}
private async Task InjectPropertiesRecursiveAsync(
object? instance,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (instance == null)
{
return;
}
// Prevent cycles
if (!visitedObjects.TryAdd(instance, 0))
{
return;
}
try
{
var plan = PropertyInjectionCache.GetOrCreatePlan(instance.GetType());
if (plan.HasProperties)
{
await InjectPropertiesFromPlanAsync(instance, plan, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
// Recurse into nested properties
await RecurseIntoNestedPropertiesAsync(instance, plan, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to inject properties for type '{instance.GetType().Name}': {ex.Message}", ex);
}
}
private Task InjectPropertiesFromPlanAsync(
object instance,
PropertyInjectionPlan plan,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (plan.SourceGeneratedProperties.Length > 0)
{
return InjectSourceGeneratedPropertiesAsync(
instance, plan.SourceGeneratedProperties, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
if (plan.ReflectionProperties.Length > 0)
{
return InjectReflectionPropertiesAsync(
instance, plan.ReflectionProperties, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
return Task.CompletedTask;
}
private Task InjectSourceGeneratedPropertiesAsync(
object instance,
PropertyInjectionMetadata[] properties,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
return ParallelTaskHelper.ForEachAsync(properties,
prop => InjectSourceGeneratedPropertyAsync(instance, prop, objectBag, methodMetadata, events, visitedObjects, cancellationToken));
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Source-gen properties are AOT-safe")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "PropertyType is preserved through source generation — annotation can't flow through PropertyInjectionMetadata interface")]
[UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "ContainingType is annotated with DynamicallyAccessedMembers in PropertyInjectionMetadata")]
private async Task InjectSourceGeneratedPropertyAsync(
object instance,
PropertyInjectionMetadata metadata,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
// First check if the property already has a value - skip if it does
// This handles nested objects that were already constructed with their properties set
var property = GetCachedPropertyInfo(metadata.ContainingType, metadata.PropertyName);
if (property != null && property.CanRead)
{
var existingValue = property.GetValue(instance);
if (existingValue != null)
{
// Property already has a value, don't overwrite it
return;
}
}
var testContext = TestContext.Current;
object? resolvedValue = null;
// Use a composite key to avoid conflicts when nested classes have properties with the same name
var cacheKey = PropertyCacheKeyGenerator.GetCacheKey(metadata);
// Check if property was pre-resolved during registration
if (testContext?.Metadata.TestDetails.TestClassInjectedPropertyArguments.TryGetValue(cacheKey, out resolvedValue) != true)
{
// Resolve the property value from the data source
resolvedValue = await ResolvePropertyDataAsync(
PropertyInitializationContext.ForSourceGenerated(
instance, metadata, objectBag, methodMetadata, events, visitedObjects, testContext),
cancellationToken);
if (resolvedValue == null)
{
return;
}
}
// Convert the value if the runtime type doesn't match the property type.
// This handles implicit/explicit conversion operators when the source generator
// doesn't know the data source type (e.g., custom data sources).
resolvedValue = CastHelper.CastIfNeeded(metadata.PropertyType, resolvedValue);
// Set the property value
metadata.SetProperty(instance, resolvedValue);
// Store the converted value for potential reuse (e.g., retries).
// Use indexer to overwrite any pre-resolved unconverted value so that
// SetCachedPropertiesOnInstance can use the value directly without re-converting.
if (testContext != null)
{
testContext.Metadata.TestDetails.GetOrCreateInjectedPropertyArguments()[cacheKey] = resolvedValue;
}
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection mode is not used in AOT")]
private Task InjectReflectionPropertiesAsync(
object instance,
(PropertyInfo Property, IDataSourceAttribute DataSource)[] properties,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
return ParallelTaskHelper.ForEachAsync(properties,
pair => InjectReflectionPropertyAsync(instance, pair.Property, pair.DataSource, objectBag, methodMetadata, events, visitedObjects, cancellationToken));
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection mode is not used in AOT")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "PropertyType is preserved through reflection discovery — annotation can't flow through PropertyInfo.PropertyType")]
private async Task InjectReflectionPropertyAsync(
object instance,
PropertyInfo property,
IDataSourceAttribute dataSource,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (property.CanRead && property.GetValue(instance) != null)
{
return;
}
var testContext = TestContext.Current;
var propertySetter = PropertySetterFactory.CreateSetter(property);
var resolvedValue = await ResolvePropertyDataAsync(
PropertyInitializationContext.ForReflection(
instance, property, dataSource, propertySetter, objectBag, methodMetadata, events, visitedObjects, testContext),
cancellationToken);
if (resolvedValue == null)
{
return;
}
// Convert the value if the runtime type doesn't match the property type.
// This handles implicit/explicit conversion operators when the source generator
// doesn't know the data source type (e.g., custom data sources).
resolvedValue = CastHelper.CastIfNeeded(property.PropertyType, resolvedValue);
propertySetter(instance, resolvedValue);
}
private Task RecurseIntoNestedPropertiesAsync(
object instance,
PropertyInjectionPlan plan,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (!plan.HasProperties)
{
return Task.CompletedTask;
}
return RecurseIntoNestedPropertiesCoreAsync(instance, plan, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
[UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "ContainingType is annotated with DynamicallyAccessedMembers in PropertyInjectionMetadata")]
private async Task RecurseIntoNestedPropertiesCoreAsync(
object instance,
PropertyInjectionPlan plan,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (plan.SourceGeneratedProperties.Length > 0)
{
for (var i = 0; i < plan.SourceGeneratedProperties.Length; i++)
{
var metadata = plan.SourceGeneratedProperties[i];
var property = GetCachedPropertyInfo(metadata.ContainingType, metadata.PropertyName);
if (property == null || !property.CanRead)
{
continue;
}
await RecurseIntoPropertyValueAsync(property.GetValue(instance), objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
}
else if (plan.ReflectionProperties.Length > 0)
{
for (var i = 0; i < plan.ReflectionProperties.Length; i++)
{
var (property, _) = plan.ReflectionProperties[i];
await RecurseIntoPropertyValueAsync(property.GetValue(instance), objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
}
}
private Task RecurseIntoPropertyValueAsync(
object? propertyValue,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
ConcurrentDictionary<object, byte> visitedObjects,
CancellationToken cancellationToken)
{
if (propertyValue == null)
{
return Task.CompletedTask;
}
if (!PropertyInjectionCache.HasInjectableProperties(propertyValue.GetType()))
{
return Task.CompletedTask;
}
return InjectPropertiesRecursiveAsync(propertyValue, objectBag, methodMetadata, events, visitedObjects, cancellationToken);
}
private Task ResolveAndCacheSourceGeneratedPropertiesAsync(
PropertyInjectionMetadata[] properties,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
CancellationToken cancellationToken)
{
return ParallelTaskHelper.ForEachAsync(properties,
prop => ResolveAndCacheSourceGeneratedPropertyAsync(prop, objectBag, methodMetadata, events, testContext, cancellationToken));
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Source-gen properties are AOT-safe")]
private async Task ResolveAndCacheSourceGeneratedPropertyAsync(
PropertyInjectionMetadata metadata,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
CancellationToken cancellationToken)
{
var cacheKey = PropertyCacheKeyGenerator.GetCacheKey(metadata);
// Check if already cached
if (testContext.Metadata.TestDetails.TestClassInjectedPropertyArguments.ContainsKey(cacheKey))
{
return;
}
// Resolve the property value from the data source
var resolvedValue = await ResolvePropertyDataAsync(
PropertyInitializationContext.ForCaching(metadata, objectBag, methodMetadata, events, testContext),
cancellationToken);
if (resolvedValue != null)
{
testContext.Metadata.TestDetails.GetOrCreateInjectedPropertyArguments().TryAdd(cacheKey, resolvedValue);
}
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection mode is not used in AOT")]
private Task ResolveAndCacheReflectionPropertiesAsync(
(PropertyInfo Property, IDataSourceAttribute DataSource)[] properties,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
CancellationToken cancellationToken)
{
return ParallelTaskHelper.ForEachAsync(properties,
pair => ResolveAndCacheReflectionPropertyAsync(pair.Property, pair.DataSource, objectBag, methodMetadata, events, testContext, cancellationToken));
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection mode is not used in AOT")]
private async Task ResolveAndCacheReflectionPropertyAsync(
PropertyInfo property,
IDataSourceAttribute dataSource,
ConcurrentDictionary<string, object?> objectBag,
MethodMetadata? methodMetadata,
TestContextEvents events,
TestContext testContext,
CancellationToken cancellationToken)
{
var cacheKey = PropertyCacheKeyGenerator.GetCacheKey(property);
// Check if already cached
if (testContext.Metadata.TestDetails.TestClassInjectedPropertyArguments.ContainsKey(cacheKey))
{
return;
}
var propertySetter = PropertySetterFactory.CreateSetter(property);
var resolvedValue = await ResolvePropertyDataAsync(
PropertyInitializationContext.ForReflectionCaching(property, dataSource, propertySetter, objectBag, methodMetadata, events, testContext),
cancellationToken);
if (resolvedValue != null)
{
testContext.Metadata.TestDetails.GetOrCreateInjectedPropertyArguments().TryAdd(cacheKey, resolvedValue);
}
}
/// <summary>
/// Resolves data from a property's data source.
/// </summary>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Property data resolution handles both modes")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "PropertyType is properly preserved through source generation")]
private async Task<object?> ResolvePropertyDataAsync(PropertyInitializationContext context, CancellationToken cancellationToken = default)
{
var dataSource = await GetInitializedDataSourceAsync(context, cancellationToken);
if (dataSource == null)
{
return null;
}
var dataGeneratorMetadata = CreateDataGeneratorMetadata(context, dataSource);
var dataRows = dataSource.GetDataRowsAsync(dataGeneratorMetadata);
await foreach (var factory in dataRows)
{
var args = await factory();
var value = TupleValueResolver.ResolveTupleValue(context.PropertyType, args);
// Resolve any Func<T> wrappers
value = await PropertyValueProcessor.ResolveTestDataValueAsync(typeof(object), value);
if (value != null)
{
#if NET
TraceScopeRegistry.RegisterFromDataSource(dataSource, args);
#endif
// EnsureInitializedAsync handles property injection and initialization.
// ObjectInitializer is phase-aware: during Discovery phase, only IAsyncDiscoveryInitializer
// objects are initialized; regular IAsyncInitializer objects are deferred to Execution phase.
await _initializationCallback.Value.EnsureInitializedAsync(
value,
context.ObjectBag,
context.MethodMetadata,
context.Events,
cancellationToken);
return value;
}
}
return null;
}
private async Task<IDataSourceAttribute?> GetInitializedDataSourceAsync(PropertyInitializationContext context, CancellationToken cancellationToken = default)
{
IDataSourceAttribute? dataSource = context.DataSource ?? context.SourceGeneratedMetadata?.CreateDataSource();
if (dataSource == null)
{
return null;
}
// Ensure the data source is initialized
return await _initializationCallback.Value.EnsureInitializedAsync(
dataSource,
context.ObjectBag,
context.MethodMetadata,
context.Events,
cancellationToken);
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Metadata creation handles both modes")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "ContainingType and PropertyType are preserved through source generation")]
private DataGeneratorMetadata CreateDataGeneratorMetadata(
PropertyInitializationContext context,
IDataSourceAttribute dataSource)
{
if (context.SourceGeneratedMetadata != null)
{
return CreateSourceGeneratedDataGeneratorMetadata(context, dataSource);
}
if (context.PropertyInfo != null)
{
return DataGeneratorMetadataCreator.CreateForPropertyInjection(
context.PropertyInfo,
context.PropertyInfo.DeclaringType!,
context.MethodMetadata,
dataSource,
_testSessionId,
context.TestContext,
context.Instance,
context.Events,
context.ObjectBag);
}
throw new InvalidOperationException("Cannot create data generator metadata: no property information available");
}
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Metadata creation handles both modes")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "ContainingType and PropertyType are preserved through source generation")]
private DataGeneratorMetadata CreateSourceGeneratedDataGeneratorMetadata(
PropertyInitializationContext context,
IDataSourceAttribute dataSource)
{
var metadata = context.SourceGeneratedMetadata!;
if (metadata.ContainingType == null)
{
throw new InvalidOperationException(
$"ContainingType is null for property '{context.PropertyName}'.");
}
// Cache the PropertyInfo lookup to avoid repeated reflection
var propertyInfo = PropertyHelper.GetPropertyInfo(metadata.ContainingType, context.PropertyName);
var propertyMetadata = new PropertyMetadata
{
IsStatic = false,
Name = context.PropertyName,
ClassMetadata = ClassMetadataHelper.GetOrCreateClassMetadata(metadata.ContainingType),
Type = context.PropertyType,
ReflectionInfo = propertyInfo,
Getter = parent => propertyInfo.GetValue(parent!)!,
ContainingTypeMetadata = ClassMetadataHelper.GetOrCreateClassMetadata(metadata.ContainingType)
};
return DataGeneratorMetadataCreator.CreateForPropertyInjection(
propertyMetadata,
context.MethodMetadata,
dataSource,
_testSessionId,
context.TestContext,
context.TestContext?.Metadata.TestDetails.ClassInstance,
context.Events,
context.ObjectBag);
}
/// <summary>
/// Gets a cached PropertyInfo for the given type and property name, avoiding repeated reflection calls.
/// </summary>
[UnconditionalSuppressMessage("Trimming", "IL2080", Justification = "Source-gen properties have their types preserved at compile time")]
private static PropertyInfo? GetCachedPropertyInfo(Type containingType, string propertyName)
{
return _propertyInfoCache.GetOrAdd((containingType, propertyName), key => key.Item1.GetProperty(key.Item2));
}
/// <summary>
/// Rents a visited objects dictionary from the pool or creates a new one.
/// </summary>
private static ConcurrentDictionary<object, byte> RentVisitedDictionary()
{
if (_visitedObjectsPool.TryTake(out var visitedObjects))
{
return visitedObjects;
}
#if NETSTANDARD2_0
return new ConcurrentDictionary<object, byte>();
#else
return new ConcurrentDictionary<object, byte>(Core.Helpers.ReferenceEqualityComparer.Instance);
#endif
}
/// <summary>
/// Returns a visited objects dictionary to the pool for reuse.
/// </summary>
private static void ReturnVisitedDictionary(ConcurrentDictionary<object, byte> visitedObjects)
{
visitedObjects.Clear();
_visitedObjectsPool.Add(visitedObjects);
}
}