You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/// <returns>A new <see cref="Scope"/> instance.</returns>
296
307
/// <exception cref="InvalidOperationException">Thrown if the host has not been initialized.</exception>
297
308
public Scope CreateScope()
298
-
=> !_initialized ? throw new InvalidOperationException("Host must be initialized before creating a scope.") : new Scope((type, s) => _factories[type](s));
309
+
{
310
+
if (!_initialized)
311
+
throw new InvalidOperationException("Host must be initialized before creating a scope.");
312
+
313
+
return new Scope((type, s) =>
314
+
{
315
+
// Direct factory lookup
316
+
if (_factories.TryGetValue(type, out var factory))
317
+
return factory(s);
318
+
319
+
// If type is an interface or abstract, resolve via descriptor → ImplementationType
320
+
var descriptor = _serviceDescriptors.FirstOrDefault(sd => sd.ServiceType == type);
321
+
if (descriptor?.ImplementationType is not null && _factories.TryGetValue(descriptor.ImplementationType, out var implFactory))
322
+
{
323
+
return implFactory(s);
324
+
}
325
+
326
+
throw new InvalidOperationException($"Cannot resolve type {type.Name} from scope.");
327
+
});
328
+
}
299
329
300
330
/// <summary>
301
331
/// Retrieves a singleton service of the specified type.
@@ -322,19 +352,26 @@ internal T GetService<T>(Scope scope) where T : class
322
352
{
323
353
var type = typeof(T);
324
354
355
+
// Fast path: direct factory lookup
325
356
if (_factories.TryGetValue(type, out var factory))
326
357
return (T)factory(scope);
327
358
328
-
// If requesting an interface, check its registration
359
+
// Lookup by descriptor
329
360
var descriptor = _serviceDescriptors.FirstOrDefault(sd => sd.ServiceType == type);
330
-
if (descriptor is not null)
361
+
if (descriptor is not null && descriptor.ImplementationType is not null)
331
362
{
332
-
if (_factories.TryGetValue(descriptor.ServiceType ?? descriptor.ServiceType, out var implFactory))
363
+
if (_factories.TryGetValue(descriptor.ImplementationType, out var implFactory))
333
364
return (T)implFactory(scope);
334
365
}
335
366
336
367
throw new InvalidOperationException($"Service of type {type.Name} is not registered.");
0 commit comments