| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Features; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | |
| | | 7 | | namespace IceRpc.Extensions.DependencyInjection.Internal; |
| | | 8 | | |
| | | 9 | | /// <summary>Implements <see cref="IDispatcherBuilder" /> for Microsoft's DI container.</summary> |
| | | 10 | | internal sealed class DispatcherBuilder : IDispatcherBuilder |
| | | 11 | | { |
| | 94 | 12 | | public IServiceProvider ServiceProvider { get; } |
| | | 13 | | |
| | | 14 | | private readonly Router _router; |
| | | 15 | | |
| | | 16 | | public IDispatcherBuilder Map<TService>(string path) where TService : notnull |
| | 14 | 17 | | { |
| | 14 | 18 | | _router.Map(path, new ServiceAdapter<TService>()); |
| | 14 | 19 | | return this; |
| | 14 | 20 | | } |
| | | 21 | | |
| | | 22 | | public IDispatcherBuilder Mount<TService>(string prefix) where TService : notnull |
| | 1 | 23 | | { |
| | 1 | 24 | | _router.Mount(prefix, new ServiceAdapter<TService>()); |
| | 1 | 25 | | return this; |
| | 1 | 26 | | } |
| | | 27 | | |
| | | 28 | | public void Route(string prefix, Action<IDispatcherBuilder> configure) => |
| | 0 | 29 | | _router.Route(prefix, router => configure(new DispatcherBuilder(router, ServiceProvider))); |
| | | 30 | | |
| | | 31 | | public IDispatcherBuilder Use(Func<IDispatcher, IDispatcher> middleware) |
| | 19 | 32 | | { |
| | 19 | 33 | | _router.Use(middleware); |
| | 19 | 34 | | return this; |
| | 19 | 35 | | } |
| | | 36 | | |
| | | 37 | | internal DispatcherBuilder(IServiceProvider provider) |
| | 15 | 38 | | : this(new Router(), provider) |
| | 15 | 39 | | { |
| | 15 | 40 | | } |
| | | 41 | | |
| | 15 | 42 | | internal IDispatcher Build() => new InlineDispatcher(async (request, cancellationToken) => |
| | 91 | 43 | | { |
| | 91 | 44 | | AsyncServiceScope asyncScope = ServiceProvider.CreateAsyncScope(); |
| | 91 | 45 | | await using ConfiguredAsyncDisposable _ = asyncScope.ConfigureAwait(false); |
| | 15 | 46 | | |
| | 91 | 47 | | request.Features = request.Features.With<IServiceProviderFeature>( |
| | 91 | 48 | | new ServiceProviderFeature(asyncScope.ServiceProvider)); |
| | 15 | 49 | | |
| | 91 | 50 | | return await _router.DispatchAsync(request, cancellationToken).ConfigureAwait(false); |
| | 15 | 51 | | }); |
| | | 52 | | |
| | 15 | 53 | | private DispatcherBuilder(Router router, IServiceProvider provider) |
| | 15 | 54 | | { |
| | 15 | 55 | | _router = router; |
| | 15 | 56 | | ServiceProvider = provider; |
| | 15 | 57 | | } |
| | | 58 | | } |