Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,28 @@ public void ClosedServicesPreferredOverOpenGenericServices()
Assert.IsType<FakeService>(service);
}

// Reproduces https://github.com/dotnet/runtime/issues/79938
[Fact]
public void ResolvingEnumerableContainingOpenGenericServiceUsesCorrectSlot()
Comment thread
steveharter marked this conversation as resolved.
Resolved
{
// Arrange
TestServiceCollection collection = new();
collection.AddTransient<IFakeOpenGenericService<PocoClass>, FakeService>();
collection.AddTransient(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>));
collection.AddSingleton<PocoClass>(); // needed for FakeOpenGenericService<>
IServiceProvider provider = CreateServiceProvider(collection);

// Act
IFakeOpenGenericService<PocoClass> service = provider.GetService<IFakeOpenGenericService<PocoClass>>();
IFakeOpenGenericService<PocoClass>[] services = provider.GetServices<IFakeOpenGenericService<PocoClass>>().ToArray();

// Assert
Assert.IsType<FakeService>(service);
Assert.Equal(2, services.Length);
Assert.True(services.Any(s => s.GetType() == typeof(FakeService)));
Assert.True(services.Any(s => s.GetType() == typeof(FakeOpenGenericService<PocoClass>)));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: ideally we'd assert some order, but the Lamar container returns a different order than other implementations.

Comment thread
steveharter marked this conversation as resolved.
Resolved
}

[Fact]
public void AttemptingToResolveNonexistentServiceReturnsNull()
{
Expand Down Expand Up @@ -905,6 +927,7 @@ public void ResolvesMixedOpenClosedGenericsAsEnumerable()
Assert.NotNull(enumerable[2]);

Assert.Equal(instance, enumerable[2]);
Assert.True(enumerable[0] is FakeService, string.Join(", ", enumerable.Select(e => e.GetType())));
Assert.IsType<FakeService>(enumerable[0]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Internal;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,71 +239,91 @@ private static bool AreCompatible(DynamicallyAccessedMemberTypes serviceDynamica
{
callSiteChain.Add(serviceType);

if (serviceType.IsConstructedGenericType &&
serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
if (!serviceType.IsConstructedGenericType ||
serviceType.GetGenericTypeDefinition() != typeof(IEnumerable<>))
{
Type itemType = serviceType.GenericTypeArguments[0];
if (ServiceProvider.VerifyAotCompatibility && itemType.IsValueType)
return null;
}

Type itemType = serviceType.GenericTypeArguments[0];
if (ServiceProvider.VerifyAotCompatibility && itemType.IsValueType)
{
// NativeAOT apps are not able to make Enumerable of ValueType services
// since there is no guarantee the ValueType[] code has been generated.
throw new InvalidOperationException(SR.Format(SR.AotCannotCreateEnumerableValueType, itemType));
}

CallSiteResultCacheLocation cacheLocation = CallSiteResultCacheLocation.Root;
ServiceCallSite[] callSites;

// If item type is not generic we can safely use descriptor cache
if (!itemType.IsConstructedGenericType &&
_descriptorLookup.TryGetValue(itemType, out ServiceDescriptorCacheItem descriptors))
{
callSites = new ServiceCallSite[descriptors.Count];
for (int i = 0; i < descriptors.Count; i++)
{
// NativeAOT apps are not able to make Enumerable of ValueType services
// since there is no guarantee the ValueType[] code has been generated.
throw new InvalidOperationException(SR.Format(SR.AotCannotCreateEnumerableValueType, itemType));
ServiceDescriptor descriptor = descriptors[i];

// Last service should get slot 0
int slot = descriptors.Count - i - 1;
// There may not be any open generics here
ServiceCallSite? callSite = TryCreateExact(descriptor, itemType, callSiteChain, slot);
Debug.Assert(callSite != null);

cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
callSites[i] = callSite;
}
}
else
{
// We need to construct a list of matching call sites in declaration order, but to ensure
// correct caching we must assign slots in reverse declaration order and with slots being
// given out first to any exact matches before any open generic matches. Therefore, we
// iterate over the descriptors twice in reverse, catching exact matches on the first pass
// and open generic matches on the second pass.

CallSiteResultCacheLocation cacheLocation = CallSiteResultCacheLocation.Root;
var callSites = new List<ServiceCallSite>();
List<KeyValuePair<int, ServiceCallSite>> callSitesByIndex = new();

// If item type is not generic we can safely use descriptor cache
if (!itemType.IsConstructedGenericType &&
_descriptorLookup.TryGetValue(itemType, out ServiceDescriptorCacheItem descriptors))
int slot = 0;
for (int i = _descriptors.Length - 1; i >= 0; i--)
{
for (int i = 0; i < descriptors.Count; i++)
if (TryCreateExact(_descriptors[i], itemType, callSiteChain, slot) is { } callSite)
{
ServiceDescriptor descriptor = descriptors[i];

// Last service should get slot 0
int slot = descriptors.Count - i - 1;
// There may not be any open generics here
ServiceCallSite? callSite = TryCreateExact(descriptor, itemType, callSiteChain, slot);
Debug.Assert(callSite != null);

cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
callSites.Add(callSite);
AddCallSite(callSite, i);
}
}
else
for (int i = _descriptors.Length - 1; i >= 0; i--)
{
int slot = 0;
// We are going in reverse so the last service in descriptor list gets slot 0
for (int i = _descriptors.Length - 1; i >= 0; i--)
if (TryCreateOpenGeneric(_descriptors[i], itemType, callSiteChain, slot, throwOnConstraintViolation: false) is { } callSite)
{
ServiceDescriptor descriptor = _descriptors[i];
ServiceCallSite? callSite = TryCreateExact(descriptor, itemType, callSiteChain, slot) ??
TryCreateOpenGeneric(descriptor, itemType, callSiteChain, slot, false);

if (callSite != null)
{
slot++;

cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
callSites.Add(callSite);
}
AddCallSite(callSite, i);
}

callSites.Reverse();
}

callSitesByIndex.Sort((a, b) => a.Key.CompareTo(b.Key));
callSites = new ServiceCallSite[callSitesByIndex.Count];
for (var i = 0; i < callSites.Length; ++i)
{
callSites[i] = callSitesByIndex[i].Value;
}

ResultCache resultCache = ResultCache.None;
if (cacheLocation == CallSiteResultCacheLocation.Scope || cacheLocation == CallSiteResultCacheLocation.Root)
void AddCallSite(ServiceCallSite callSite, int index)
{
resultCache = new ResultCache(cacheLocation, callSiteKey);
slot++;

cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
callSitesByIndex.Add(new(index, callSite));
}
}

return _callSiteCache[callSiteKey] = new IEnumerableCallSite(resultCache, itemType, callSites.ToArray());
ResultCache resultCache = ResultCache.None;
if (cacheLocation == CallSiteResultCacheLocation.Scope || cacheLocation == CallSiteResultCacheLocation.Root)
{
resultCache = new ResultCache(cacheLocation, callSiteKey);
}

return null;
return _callSiteCache[callSiteKey] = new IEnumerableCallSite(resultCache, itemType, callSites);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1125,6 +1125,32 @@ public async Task ProviderDisposeAsyncCallsDisposeAsyncOnceOnServices()
Assert.Equal(1, disposable.DisposeCount);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void ValidateOnBuild_True_ResolvesConstrainedOpenGeneric(bool validateOnBuild)
{
var services = new ServiceCollection();

services.AddTransient<IBB<AA>, BB>();
services.AddTransient(typeof(IBB<>), typeof(GenericBB<>));
services.AddTransient(typeof(IBB<>), typeof(ConstrainedGenericBB<>));

var serviceProvider = services.BuildServiceProvider(new ServiceProviderOptions() { ValidateOnBuild = validateOnBuild });
var handlers = serviceProvider
.GetServices<IBB<AA>>()
.ToList();

Assert.Equal(3, handlers.Count);
var handlersTypes = handlers
.Select(h => h.GetType())
.ToList();

Assert.Contains(typeof(BB), handlersTypes);
Assert.Contains(typeof(GenericBB<AA>), handlersTypes);
Assert.Contains(typeof(ConstrainedGenericBB<AA>), handlersTypes);
Comment thread
steveharter marked this conversation as resolved.
Resolved
}

private class FakeDisposable : IDisposable
{
public bool IsDisposed { get; private set; }
Expand Down Expand Up @@ -1319,5 +1345,11 @@ public Aa(A a)
}
public A PropertyA { get; }
}
private interface IAA { }
private interface IBB<T> { }
private class AA : IAA { }
private class BB : IBB<AA> { }
private class GenericBB<T> : IBB<T> { }
private class ConstrainedGenericBB<T> : IBB<T> where T : IAA { }
}
}