diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs index cff40d1fbb1ec..83b3e4f70122d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs @@ -167,7 +167,7 @@ private Func CreateServiceAccessor(Type serv internal void ReplaceServiceAccessor(ServiceCallSite callSite, Func accessor) { - _realizedServices[callSite.ImplementationType] = accessor; + _realizedServices[callSite.ServiceType] = accessor; } internal IServiceScope CreateScope() diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceLookup/CallSiteFactoryTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceLookup/CallSiteFactoryTest.cs index da24dca4e92cf..56f0982c0d1c5 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceLookup/CallSiteFactoryTest.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceLookup/CallSiteFactoryTest.cs @@ -6,16 +6,39 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; +using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Microsoft.Extensions.DependencyInjection.Tests; using Xunit; namespace Microsoft.Extensions.DependencyInjection.ServiceLookup { public class CallSiteFactoryTest { + [Fact] + public void GetService_FactoryCallSite_Transient_DoesNotFail() + { + var collection = new ServiceCollection(); + collection.Add(ServiceDescriptor.Describe(typeof(FakeService), (sp) => new FakeService(), ServiceLifetime.Transient)); + collection.Add(ServiceDescriptor.Describe(typeof(IFakeService), (sp) => new FakeService(), ServiceLifetime.Transient)); + + using ServiceProvider serviceProvider = collection.BuildServiceProvider(ServiceProviderMode.Dynamic); + Type expectedType = typeof(FakeService); + + Assert.Equal(expectedType, serviceProvider.GetService(typeof(IFakeService)).GetType()); + Assert.Equal(expectedType, serviceProvider.GetService(typeof(FakeService)).GetType()); + + for (int i = 0; i < 50; i++) + { + Assert.Equal(expectedType, serviceProvider.GetService(typeof(IFakeService)).GetType()); + Assert.Equal(expectedType, serviceProvider.GetService(typeof(FakeService)).GetType()); + Thread.Sleep(10); // Give the background thread time to compile + } + } + [Fact] public void CreateCallSite_Throws_IfTypeHasNoPublicConstructors() {