runtime: Microsoft.Extensions.Http.Resilience - Cannot access a disposed object. - Integrationtest with WebApplicationFactory

Problem with .AddStandardResilienceHandler(); when used in integration test with custom web factory and when there is more than one test.

I have a service that uses HttpClients to 3rd party endpoints. On this one, I use the.AddStandardResilienceHandler(); I set this up in my startup.cs then I have an integration test where I use the WebApplicationFactory

All works fine, but after some lib updates, I start getting random exceptions from my tests. If I run one test at a time with no problem, it seems to be shared resource issues when they run in parallel.

The tests randomly give me:

  Message: 
System.ObjectDisposedException : Cannot access a disposed object.
Object name: 'IServiceProvider'.

And:

System.InvalidCastException: Unable to cast object of type 'System.TimeSpan' to type 'System.String'.
   at __OptionValidationGeneratedAttributes.<Validators_g>F8B1F3D42962A35D8FF1B1489612AEF6C36F3713335EFF79DB68A25973333C495____SourceGen__RangeAttribute.IsValid(Object value)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext)
   at System.ComponentModel.DataAnnotations.Validator.TryValidate(Object value, ValidationContext validationContext, ValidationAttribute attribute, ValidationError& validationError)
   at System.ComponentModel.DataAnnotations.Validator.GetValidationErrors(Object value, ValidationContext validationContext, IEnumerable`1 attributes, Boolean breakOnFirstError)
   at System.ComponentModel.DataAnnotations.Validator.TryValidateValue(Object value, ValidationContext validationContext, ICollection`1 validationResults, IEnumerable`1 validationAttributes)
   at Microsoft.Extensions.Http.Resilience.__HttpTimeoutStrategyOptionsValidator__.

It does not happen all the time but mostly every time.

I have tried fixture, using the same client that’s created on all test methods but it seems like a disposal is happening. But next time there is some expectation that the resilience services shall exist somehow. Not all services are not resettled. Some singleton was added once I guess.

 public HttpClient CreateClient(ITestOutputHelper testOutputHelper = null)
 {
     _waf = new WebApplicationFactory<TProgram>()
        .WithWebHostBuilder(builder =>
        {

If I remove the .AddStandardResilienceHandler(); from my setup of the HTTP client all works fine.

I also tried to remove the added services and override them in

 builder.ConfigureTestServices(services =>
 {

But that will not work because it’s still have added the resilience stuff before I reach this area.

So it seams like: First it creates my client with resilience, then I ran the fist FACT test. Then a second one. I have 2 tests one for success and one for failure. If I remove one of the test all works fine. But as soon I share the client in many test this happens.

Not sure if there is som clean-up, or dispose issues with the resilience setup? I have followed the basic guidelines to setup integration tests in .net

Have I missed something? Or is this a known bug? I can see there is a bug reported where it seams to be a shared setting for all services atm so we can’t override settings on different once. Maybe that’s related here?

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 4
  • Comments: 29 (16 by maintainers)

Commits related to this issue

Most upvoted comments

I’m not at a computer until tomorrow now, but I had to use ILSpy to get the code because it was compiled into the Resilience library, rather than being generated into my own project.

never mind. I have created an isolated simple repro and I can see the issue now.

parallelizeTestCollections helps here too.

I have submitted the fix to main and 8.0 servicing branches. Hopefully, this will be included in the February 8.0 servicing release.

OK, so the problem is this:

  • Through the code generator, we’re creating some static instances of the various validation attributes. In this case, we’re creating a static instance of the RangeAttribute class.

  • We then call RangeAttribute.IsValid from multiple threads, since the expectation was that IsValid is a read-only operation and so can be safely called in parallel. Clearly, RangeAttribute.IsValid was not designed for parallel execution.

@tarekgh I think the InvalidCastException part of this problem has to do with the config validation code gen and how we’re handling some racy initialization in the attribute. Can you take a look please?

One final data point, if I change my xunit configuration to have "parallelizeTestCollections": false then the issue goes away when I run all the tests in the same test run.

Looking at the code, there might be a race condition where the casts (string)Minimum or/and (string)Maximum fail if those values are already initialized with a TimeSpan value if Initialized hasn’t been set to true yet if the validator runs concurrently. Source

I’m getting the Unable to cast object of type 'System.TimeSpan' to type 'System.String' error too (but not the dispose-related one).

What info would you need to diagnose this? Would a complete solution that shows the problem help?