Skip to content

Commit 55890be

Browse files
committed
GetService now handles interfaces
1 parent b7fa58e commit 55890be

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

SimpleInjection/Injection/Host.cs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,30 @@ internal T GetService<T>(Scope scope) where T : class
255255
{
256256
var type = typeof(T);
257257

258-
return !_factories.TryGetValue(type, out var factory)
259-
? throw new InvalidOperationException($"Service of type {type.Name} is not registered.")
260-
: (T)factory(scope);
258+
// Try direct factory lookup first
259+
if (_factories.TryGetValue(type, out var factory))
260+
return (T)factory(scope);
261+
262+
// If not found and type is interface, try to find a concrete implementation
263+
if (type.IsInterface)
264+
{
265+
// Find all descriptors that implement this interface
266+
var implementations = _serviceDescriptors
267+
.Where(sd => type.IsAssignableFrom(sd.ServiceType) && !sd.ServiceType.IsInterface && !sd.ServiceType.IsAbstract)
268+
.ToList();
269+
270+
if (implementations.Count == 1)
271+
{
272+
var implType = implementations[0].ServiceType;
273+
if (_factories.TryGetValue(implType, out var implFactory))
274+
return (T)implFactory(scope);
275+
}
276+
else if (implementations.Count > 1)
277+
{
278+
throw new InvalidOperationException($"Multiple implementations found for interface {type.Name}. Please register only one or use a more specific type.");
279+
}
280+
}
281+
282+
throw new InvalidOperationException($"Service of type {type.Name} is not registered.");
261283
}
262284
}

SimpleInjection/SimpleInjection.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
1010
<PackageId>SimpleInjection</PackageId>
11-
<Version>0.9.6.1</Version>
11+
<Version>0.9.6.2</Version>
1212
<Authors>Derek Gooding</Authors>
1313
<Company>Derek Gooding</Company>
1414
<Description>

0 commit comments

Comments
 (0)