.NET Core: Cannot Access a Disposed Object

Problem:

I encountered this error: “Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection”

Discussion:

The message itself indicates that the cause may be hard to track down.  Thankfully, I came across the article below to troubleshoot.

I have a public async void method.  It uses a dependency injection object and it calls one of the async methods of this DI object.

Solution:

I changed the method from

public async void Method()

to

public async Task Method()

 

Reference:

https://thinkrethink.net/2017/12/22/cannot-access-a-disposed-object-in-asp-net-core-when-injecting-dbcontext/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s