|
3 | 3 | using Microsoft.AspNetCore.Http.Metadata;
|
4 | 4 | using Microsoft.AspNetCore.Http.RequestDelegateGenerator;
|
5 | 5 | using Microsoft.Extensions.DependencyInjection;
|
| 6 | +using Microsoft.Extensions.Logging.Abstractions; |
| 7 | + |
6 | 8 | namespace Microsoft.AspNetCore.Http.Generators.Tests;
|
7 | 9 |
|
8 | 10 | public partial class RequestDelegateCreationTests : RequestDelegateCreationTestBase
|
@@ -197,4 +199,44 @@ public async Task SupportsMultipleKeyedAndNonKeyedServices()
|
197 | 199 | Assert.IsType<TestService>(httpContext.Items["arg2"]);
|
198 | 200 | Assert.Same(myOriginalService2, httpContext.Items["arg3"]);
|
199 | 201 | }
|
| 202 | + |
| 203 | + [Fact] |
| 204 | + public async Task ThrowsIfDiContainerDoesNotSupportKeyedServices() |
| 205 | + { |
| 206 | + var source = """ |
| 207 | + app.MapGet("/", (HttpContext context, [FromKeyedServices("service1")] TestService arg1) => |
| 208 | + { |
| 209 | + context.Items["arg1"] = arg1; |
| 210 | + }); |
| 211 | + """; |
| 212 | + var (_, compilation) = await RunGeneratorAsync(source); |
| 213 | + var serviceProvider = new MockServiceProvider(); |
| 214 | + if (!IsGeneratorEnabled) |
| 215 | + { |
| 216 | + var runtimeException = Assert.Throws<InvalidOperationException>(() => GetEndpointFromCompilation(compilation, serviceProvider: serviceProvider)); |
| 217 | + Assert.Equal("Unable to resolve FromKeyedServicesAttribute. This service provider doesn't support keyed services.", runtimeException.Message); |
| 218 | + return; |
| 219 | + } |
| 220 | + var endpoint = GetEndpointFromCompilation(compilation, serviceProvider: serviceProvider); |
| 221 | + |
| 222 | + var httpContext = CreateHttpContext(serviceProvider); |
| 223 | + var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await endpoint.RequestDelegate(httpContext)); |
| 224 | + Assert.Equal("Unable to resolve FromKeyedServicesAttribute. This service provider doesn't support keyed services.", exception.Message); |
| 225 | + } |
| 226 | + |
| 227 | + private class MockServiceProvider : IServiceProvider, ISupportRequiredService |
| 228 | + { |
| 229 | + public object GetService(Type serviceType) |
| 230 | + { |
| 231 | + if (serviceType == typeof(Microsoft.Extensions.Logging.ILoggerFactory)) |
| 232 | + { |
| 233 | + return NullLoggerFactory.Instance; |
| 234 | + } |
| 235 | + return null; |
| 236 | + } |
| 237 | + public object GetRequiredService(Type serviceType) |
| 238 | + { |
| 239 | + return GetService(serviceType); |
| 240 | + } |
| 241 | + } |
200 | 242 | }
|
0 commit comments