Skip to content

Commit 5919021

Browse files
add initial support for KeyedService.AnyKey
1 parent b03a743 commit 5919021

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

src/Ninject.Web.AspNetCore/NinjectServiceProvider.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ public object GetKeyedService(Type serviceType, object serviceKey)
8282
object result;
8383
if (!IsListType(serviceType, out var elementType))
8484
{
85+
EnsureNotAnyKey(serviceKey, serviceType);
8586
result = _resolutionRoot.TryGet(serviceType,
8687
metadata => DoesMetadataMatchServiceKey(serviceKey, metadata));
8788
}
@@ -100,6 +101,7 @@ public object GetRequiredKeyedService(Type serviceType, object serviceKey)
100101
{
101102
if (!IsListType(serviceType, out var elementType))
102103
{
104+
EnsureNotAnyKey(serviceKey, serviceType);
103105
return _resolutionRoot.Get(serviceType, metadata => DoesMetadataMatchServiceKey(serviceKey, metadata));
104106
}
105107
else
@@ -111,8 +113,22 @@ public object GetRequiredKeyedService(Type serviceType, object serviceKey)
111113
}
112114
}
113115

116+
private void EnsureNotAnyKey(object serviceKey, Type serviceType)
117+
{
118+
if (serviceKey == KeyedService.AnyKey)
119+
{
120+
throw new InvalidOperationException($"Not allowed to resolve a service {serviceType} with the KeyedService.AnyKey. " +
121+
$"That's only supported when resolving collections of services.");
122+
}
123+
}
124+
125+
114126
private static bool DoesMetadataMatchServiceKey(object serviceKey, IBindingMetadata metadata)
115127
{
128+
if (serviceKey == KeyedService.AnyKey)
129+
{
130+
return HasServiceKeyMetadata(metadata);
131+
}
116132
return metadata.Get<ServiceKey>(nameof(ServiceKey))?.Key == serviceKey;
117133
}
118134
#endif

0 commit comments

Comments
 (0)