7

We have windows service that hosts web api and does some calculation job in background. From time to time we get exception:

2019-12-27 11:49:15.525 +01:00 [Error] [Serilog.Log.Write] Unhandled exception caught. Runtime is terminating : True
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at MediatR.ServiceFactoryExtensions.GetInstances[T](ServiceFactory factory)
   at MediatR.Internal.RequestHandlerWrapperImpl`2.Handle(IRequest`1 request, CancellationToken cancellationToken, ServiceFactory serviceFactory)
   at MediatR.Mediator.Send[TResponse](IRequest`1 request, CancellationToken cancellationToken)
   at DataProcessor.Enricher.ChangeTracking.LegacyDataChangeTracker.SendForEnrichment(TurbineTimeCounters turbineTimeCounters, Unit unit)
   at DataProcessor.Enricher.ChangeTracking.LegacyDataChangeTracker.<ProcessEventsAndHistData>b__29_1(Unit unit)
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__139_1(Object state)
   at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

We don't have any exceptions from built in DI on startup, thus dependencies are configured correctly.

I made investigation. MediatR's ServiceFactory is a delegate to Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService method.

ServiceProviderEngineScope is disposed at the time, when MediatR call's for it. https://github.com/aspnet/DependencyInjection/blob/master/src/DI/ServiceLookup/ServiceProviderEngineScope.cs

Any ideas why ServiceProviderEngineScope had been disposed before MediatR called it?

MediatR version 7.0.0.

Asp.Net core 3.0.

cl0ud
  • 1,524
  • 11
  • 27
  • Are you injecting `IMediator` into your handler? – cl0ud Jan 27 '20 at 16:41
  • No, handler has logger and business logic classes. – Yaroslav Ryabyi Jan 27 '20 at 17:01
  • 1
    Have you checked that you are awaiting all `async` calls? – cl0ud Jan 27 '20 at 20:59
  • Have you seen this comment on a similar GitHub issue: [link](https://github.com/aspnet/DependencyInjection/issues/440#issuecomment-236862811) I had a similar issue with the IServiceProvider.CreateScope(). In very few occasions it throwed a System.ObjectDisposedException. With the hint from the link I got rid of it – Lauryx May 28 '20 at 09:16

0 Answers0