Skip to content

Commit f670e6d

Browse files
committed
Fix interface constructor bug
1 parent 55890be commit f670e6d

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

SimpleInjection/Injection/Host.cs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,27 @@ private void CreateSingletonFactory(ServiceDescriptor descriptor)
178178
{
179179
if (!_singletonInstances.TryGetValue(serviceType, out var instance))
180180
{
181-
instance = CreateInstance(serviceType, scope);
181+
var typeToCreate = serviceType;
182+
if (serviceType.IsInterface)
183+
{
184+
// Find all concrete implementations for this interface
185+
var implementations = _serviceDescriptors
186+
.Where(sd => serviceType.IsAssignableFrom(sd.ServiceType) && !sd.ServiceType.IsInterface && !sd.ServiceType.IsAbstract)
187+
.ToList();
188+
if (implementations.Count == 1)
189+
{
190+
typeToCreate = implementations[0].ServiceType;
191+
}
192+
else if (implementations.Count > 1)
193+
{
194+
throw new InvalidOperationException($"Multiple implementations found for interface {serviceType.Name}. Please register only one or use a more specific type.");
195+
}
196+
else
197+
{
198+
throw new InvalidOperationException($"No implementation found for interface {serviceType.Name}.");
199+
}
200+
}
201+
instance = CreateInstance(typeToCreate, scope);
182202
_singletonInstances[serviceType] = instance;
183203
}
184204
return instance;

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.2</Version>
11+
<Version>0.9.6.3</Version>
1212
<Authors>Derek Gooding</Authors>
1313
<Company>Derek Gooding</Company>
1414
<Description>

0 commit comments

Comments
 (0)