'System.ObjectDisposedException: 'Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope
I have an async controller and I am trying to call two different Async functions from it. like this
public async void Approvefiles(string[] data)
{
var response = await _mediator.Send(new persons.Query(data));
await _mediator.Send(new employees.Query(data));
}
All looks good to me, But this throws an error
System.ObjectDisposedException: 'Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.'
Can anyone point out what I am doing wrong here? And this error doesn't occur if I call only one async function (for exaple persons.Query only).
Solution 1:[1]
Your problem is here:
public async void Approvefiles(string[] data)
async void
methods pretty much means that nothing will wait for that method to finish before continuing (as well as causing a host of other problems).
So I imagine your request scope is getting cleaned up before your second _mediator.Send
call, meaning nothing can be resolved.
You need to change the signature to:
public async Task Approvefiles(string[] data)
Then await that method as needed in your controller to make sure it completes before your request ends.
There's an answer here about why async void is bad, for more detail.
Solution 2:[2]
My two cents. Mine was a petty mistake, I forgot to await an async call.
So I had this async extension method as follows.
public static async Task<T> DeserializePostInMeWurkFormat<T>(this HttpClient httpClient, string route, HttpContent? content)
{
var postResult = await httpClient.PostAsync(route, content);
postResult.EnsureSuccessStatusCode();
postResult.IsSuccessStatusCode.Should().BeTrue();
var stringResponse = await postResult.Content.ReadAsStringAsync();
var response = stringResponse.DeserializeWithCamelCasePolicy<T>();
return response!;
}
And I was calling without awaiting it as follows.
var postsResult = _client.DeserializePostInMeWurkFormat<CompanyOnboardDto>(OnboardCompanyRequest.Route, data);
Got the exception as follows.
System.ObjectDisposedException HResult=0x80131622 Message=Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) has already been disposed. Source=Autofac
Corrected the call as follows with await, and now it works fine.
var postsResult = await _client.DeserializePostInMeWurkFormat<CompanyOnboardDto>(OnboardCompanyRequest.Route, data);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alistair Evans |
Solution 2 | VivekDev |