|
1 | 1 | using Gufel.Dispatcher.Base.Dispatcher; |
2 | | -using Microsoft.AspNetCore.Http; |
3 | 2 | using Microsoft.Extensions.DependencyInjection; |
4 | 3 |
|
5 | 4 | namespace Gufel.Dispatcher.Implement |
6 | 5 | { |
7 | | - public class Dispatcher : IDispatcher, IDisposable |
| 6 | + public sealed class Dispatcher(IServiceProvider serviceProvider) : IDispatcher |
8 | 7 | { |
9 | | - private readonly IServiceScope? _serviceScope; |
10 | | - private readonly IServiceProvider _serviceProvider; |
11 | | - |
12 | | - public Dispatcher( |
13 | | - IServiceScopeFactory serviceScope, |
14 | | - IHttpContextAccessor httpContextAccessor) |
15 | | - { |
16 | | - if (httpContextAccessor.HttpContext != null) |
17 | | - { |
18 | | - _serviceProvider = httpContextAccessor.HttpContext.RequestServices; |
19 | | - } |
20 | | - else |
21 | | - { |
22 | | - _serviceScope = serviceScope.CreateScope(); |
23 | | - _serviceProvider = _serviceScope.ServiceProvider; |
24 | | - } |
25 | | - } |
26 | | - |
27 | 8 | public async Task Dispatch<TRequest>(TRequest request, CancellationToken cancellation) |
28 | 9 | where TRequest: IRequest |
29 | 10 | { |
30 | | - var pipeLines = _serviceProvider.GetServices<IPipelineHandler<TRequest>>(); |
| 11 | + var pipeLines = serviceProvider.GetServices<IPipelineHandler<TRequest>>(); |
31 | 12 | foreach (var pipeline in pipeLines) |
32 | 13 | { |
33 | 14 | await pipeline.Handle(request, cancellation); |
34 | 15 | } |
35 | 16 |
|
36 | | - var handler = _serviceProvider.GetRequiredService<IRequestHandler<TRequest>>(); |
| 17 | + var handler = serviceProvider.GetRequiredService<IRequestHandler<TRequest>>(); |
37 | 18 | await handler.Handle(request, cancellation); |
38 | 19 | } |
39 | 20 |
|
40 | 21 | public async Task<TResponse> Dispatch<TRequest, TResponse>(TRequest request, CancellationToken cancellation) |
41 | 22 | where TRequest : IRequest<TResponse> |
42 | 23 | where TResponse : IResponse |
43 | 24 | { |
44 | | - var pipeLines = _serviceProvider.GetServices<IPipelineHandler<TRequest, TResponse>>(); |
| 25 | + var pipeLines = serviceProvider.GetServices<IPipelineHandler<TRequest, TResponse>>(); |
45 | 26 | foreach (var pipeline in pipeLines) |
46 | 27 | { |
47 | 28 | await pipeline.Handle(request, cancellation); |
48 | 29 | } |
49 | 30 |
|
50 | | - var handler = _serviceProvider.GetRequiredService<IRequestHandler<TRequest, TResponse>>(); |
| 31 | + var handler = serviceProvider.GetRequiredService<IRequestHandler<TRequest, TResponse>>(); |
51 | 32 | return await handler.Handle(request, cancellation); |
52 | 33 | } |
53 | | - |
54 | | - protected virtual void Dispose(bool disposing) |
55 | | - { |
56 | | - _serviceScope?.Dispose(); |
57 | | - } |
58 | | - |
59 | | - public void Dispose() |
60 | | - { |
61 | | - Dispose(true); |
62 | | - GC.SuppressFinalize(this); |
63 | | - } |
64 | 34 | } |
65 | 35 | } |
0 commit comments