55using System . Runtime . ExceptionServices ;
66using System . Threading ;
77using System . Threading . Tasks ;
8+ using Microsoft . Extensions . DependencyInjection ;
89
910namespace MicroBatchFramework
1011{
@@ -15,7 +16,7 @@ public sealed class BatchEngineService : IHostedService
1516 MethodInfo methodInfo ;
1617 IApplicationLifetime appLifetime ;
1718 ILogger < BatchEngine > logger ;
18- IServiceProvider provider ;
19+ IServiceScope scope ;
1920 IBatchInterceptor interceptor ;
2021 Task runningTask ;
2122 CancellationTokenSource cancellationTokenSource ;
@@ -31,23 +32,23 @@ public BatchEngineService(IApplicationLifetime appLifetime, Type type, MethodInf
3132 this . type = type ;
3233 this . methodInfo = methodInfo ;
3334 this . appLifetime = appLifetime ;
34- this . provider = provider ;
35+ this . scope = provider . CreateScope ( ) ;
3536 this . logger = logger ;
3637 this . interceptor = ( provider . GetService ( typeof ( IBatchInterceptor ) ) as IBatchInterceptor ) ?? NullBatchInterceptor . Default ;
3738 this . cancellationTokenSource = new CancellationTokenSource ( ) ;
3839 }
3940
4041 public async Task StartAsync ( CancellationToken cancellationToken )
4142 {
42- await interceptor . OnBatchEngineBeginAsync ( provider , logger ) ;
43+ await interceptor . OnBatchEngineBeginAsync ( scope . ServiceProvider , logger ) ;
4344
4445 // raise after all event registered
4546 appLifetime . ApplicationStarted . Register ( async state =>
4647 {
4748 var self = ( BatchEngineService ) state ;
4849 try
4950 {
50- var engine = new BatchEngine ( self . logger , self . provider , self . interceptor , self . cancellationTokenSource . Token ) ;
51+ var engine = new BatchEngine ( self . logger , scope . ServiceProvider , self . interceptor , self . cancellationTokenSource . Token ) ;
5152 if ( self . methodInfo != null )
5253 {
5354 self . runningTask = engine . RunAsync ( self . type , self . methodInfo , self . args ) ;
@@ -85,6 +86,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
8586 finally
8687 {
8788 await interceptor . OnBatchEngineEndAsync ( ) ;
89+ scope . Dispose ( ) ;
8890 }
8991 }
9092 }
0 commit comments