Skip to content

Throw if resolving keyed service from non-keyed container #53051

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,11 @@ internal static void EmitKeyedServiceParameterPreparation(this EndpointParameter
{
codeWriter.WriteLine(endpointParameter.EmitParameterDiagnosticComment());

codeWriter.WriteLine("if (httpContext.RequestServices.GetService<IServiceProviderIsService>() is not IServiceProviderIsKeyedService)");
codeWriter.StartBlock();
codeWriter.WriteLine(@"throw new InvalidOperationException($""Unable to resolve {nameof(FromKeyedServicesAttribute)}. This service provider doesn't support keyed services."");");
codeWriter.EndBlock();

var assigningCode = endpointParameter.IsOptional ?
$"httpContext.RequestServices.GetKeyedService<{endpointParameter.Type}>({endpointParameter.KeyedServiceKey});" :
$"httpContext.RequestServices.GetRequiredKeyedService<{endpointParameter.Type}>({endpointParameter.KeyedServiceKey})";
Expand Down
4 changes: 4 additions & 0 deletions src/Http/Http.Extensions/src/RequestDelegateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,10 @@ private static Expression CreateArgument(ParameterInfo parameter, RequestDelegat
}
else if (parameterCustomAttributes.OfType<FromKeyedServicesAttribute>().FirstOrDefault() is { } keyedServicesAttribute)
{
if (factoryContext.ServiceProviderIsService is not IServiceProviderIsKeyedService)
{
throw new InvalidOperationException($"Unable to resolve {nameof(FromKeyedServicesAttribute)}. This service provider doesn't support keyed services.");
}
var key = keyedServicesAttribute.Key;
return BindParameterFromKeyedService(parameter, key, factoryContext);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Http.RequestDelegateGenerator;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.AspNetCore.Http.Generators.Tests;

public partial class RequestDelegateCreationTests : RequestDelegateCreationTestBase
Expand Down Expand Up @@ -197,4 +199,44 @@ public async Task SupportsMultipleKeyedAndNonKeyedServices()
Assert.IsType<TestService>(httpContext.Items["arg2"]);
Assert.Same(myOriginalService2, httpContext.Items["arg3"]);
}

[Fact]
public async Task ThrowsIfDiContainerDoesNotSupportKeyedServices()
{
var source = """
app.MapGet("/", (HttpContext context, [FromKeyedServices("service1")] TestService arg1) =>
{
context.Items["arg1"] = arg1;
});
""";
var (_, compilation) = await RunGeneratorAsync(source);
var serviceProvider = new MockServiceProvider();
if (!IsGeneratorEnabled)
{
var runtimeException = Assert.Throws<InvalidOperationException>(() => GetEndpointFromCompilation(compilation, serviceProvider: serviceProvider));
Assert.Equal("Unable to resolve FromKeyedServicesAttribute. This service provider doesn't support keyed services.", runtimeException.Message);
return;
}
var endpoint = GetEndpointFromCompilation(compilation, serviceProvider: serviceProvider);

var httpContext = CreateHttpContext(serviceProvider);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await endpoint.RequestDelegate(httpContext));
Assert.Equal("Unable to resolve FromKeyedServicesAttribute. This service provider doesn't support keyed services.", exception.Message);
}

private class MockServiceProvider : IServiceProvider, ISupportRequiredService
{
public object GetService(Type serviceType)
{
if (serviceType == typeof(Microsoft.Extensions.Logging.ILoggerFactory))
{
return NullLoggerFactory.Instance;
}
return null;
}
public object GetRequiredService(Type serviceType)
{
return GetService(serviceType);
}
}
}