Skip to content

Commit e90084e

Browse files
committed
Fixed Creating Interface instance problem.
1 parent 7929d38 commit e90084e

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

SimpleInjection/Injection/Host.cs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,20 +206,49 @@ private void CreateTransientFactory(ServiceDescriptor descriptor)
206206
private object CreateInstance(Type type, Scope scope)
207207
{
208208
var constructor = type.GetConstructors().FirstOrDefault()
209-
?? throw new InvalidOperationException($"No public constructor found for type {type.Name}");
209+
?? throw new InvalidOperationException($"No public constructor found for type {type.Name}");
210210

211211
var parameters = constructor.GetParameters();
212212
var arguments = new object[parameters.Length];
213213

214214
for (var i = 0; i < parameters.Length; i++)
215215
{
216216
var paramType = parameters[i].ParameterType;
217-
if (!_factories.TryGetValue(paramType, out var factory))
217+
218+
if (paramType.IsInterface)
218219
{
219-
throw new InvalidOperationException($"Cannot resolve dependency {paramType.Name} for {type.Name}");
220+
// Find the concrete implementation for this interface
221+
var implementations = _serviceDescriptors
222+
.Where(sd => paramType.IsAssignableFrom(sd.ServiceType) && !sd.ServiceType.IsInterface && !sd.ServiceType.IsAbstract)
223+
.ToList();
224+
225+
if (implementations.Count == 1)
226+
{
227+
var implType = implementations[0].ServiceType;
228+
if (_factories.TryGetValue(implType, out var implFactory))
229+
{
230+
arguments[i] = implFactory(scope);
231+
continue;
232+
}
233+
}
234+
else if (implementations.Count > 1)
235+
{
236+
throw new InvalidOperationException($"Multiple implementations found for interface {paramType.Name} when resolving dependency for {type.Name}. Please register only one or use a more specific type.");
237+
}
238+
239+
throw new InvalidOperationException($"No implementation found for interface {paramType.Name} when resolving dependency for {type.Name}");
220240
}
241+
else
242+
{
243+
// It's a concrete type, look it up directly
244+
if (_factories.TryGetValue(paramType, out var factory))
245+
{
246+
arguments[i] = factory(scope);
247+
continue;
248+
}
221249

222-
arguments[i] = factory(scope);
250+
throw new InvalidOperationException($"Cannot resolve dependency {paramType.Name} for {type.Name}");
251+
}
223252
}
224253

225254
return constructor.Invoke(arguments);

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

0 commit comments

Comments
 (0)