Skip to content

Commit dc01389

Browse files
committed
Add handling for null key in FromKeyedServicesAttribute.
1 parent 2313f8b commit dc01389

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/Autofac.Extensions.DependencyInjection/FromKeyedServicesAttributeExtensions.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,16 @@ internal static class FromKeyedServicesAttributeExtensions
2626
public static object? ResolveParameter(this FromKeyedServicesAttribute attribute, ParameterInfo parameter, IComponentContext context)
2727
{
2828
// Adapter for FromKeyedServicesAttribute to work like Autofac.Features.AttributeFilters.KeyFilterAttribute.
29-
context.TryResolveKeyed(attribute.Key, parameter.ParameterType, out var value);
30-
return value;
29+
object? instance;
30+
if (attribute.Key is null)
31+
{
32+
// No key in the attribute means resolve by type.
33+
context.TryResolve(parameter.ParameterType, out instance);
34+
return instance;
35+
}
36+
37+
context.TryResolveKeyed(attribute.Key, parameter.ParameterType, out instance);
38+
return instance;
3139
}
3240

3341
/// <summary>
@@ -40,6 +48,12 @@ internal static class FromKeyedServicesAttributeExtensions
4048
public static bool CanResolveParameter(this FromKeyedServicesAttribute attribute, ParameterInfo parameter, IComponentContext context)
4149
{
4250
// Adapter for FromKeyedServicesAttribute to work like Autofac.Features.AttributeFilters.KeyFilterAttribute.
51+
if (attribute.Key is null)
52+
{
53+
// No key in the attribute means resolve by type.
54+
return context.ComponentRegistry.IsRegistered(new Autofac.Core.TypedService(parameter.ParameterType));
55+
}
56+
4357
return context.ComponentRegistry.IsRegistered(new Autofac.Core.KeyedService(attribute.Key, parameter.ParameterType));
4458
}
4559
}

0 commit comments

Comments
 (0)