Search code examples
c#asp.net-coretimerentity-framework-coreblazor-server-side

How to resolve a ObjectDisposedException that occurs in a Blazor Component using a Timer


I am currently trying to use a Timer (System.Timers) within a Blazor component to update an entity using an Injected DBContext. However when it reaches the Save Changes method it simply shows the following error

enter image description here Disposed Exception

Here is the my Startup.cs file DbContext section: Startup.cs

My Blazor Component CS looks like this: Blazor Component

What I think the Problem Is

I think the problem is that the Timer class is on a different thread and therefore isn't in scope to access to the DbContext.

What I don't know is, if I am right, how to pass the DbContext properly to the Timer or how to call the Save Changes method from the main thread.

I did try to use a DBContextPool (as shown below) but it doesn't work. I am guessing it's still due to the thread being different from the main thread.

DbContextPool

If you need any more details please just let me know so I can gather the exact details.

Update 1 07/20/2020

I attempted to move the logic into a service. That service then has a DbContext injected into it however I got the same error message but the error happened in the new ActionService class.

Here is the new ActionService

enter image description here

And here is the Startup.cs change

enter image description here

Here is the Blazor Component Update

enter image description here


Solution

  • The error message indicates your DbContext was disposed of before your timer fires. It's not related to the thread the code executes on (though as a separate issue, DbContext instances are not thread-safe).

    I have not used Blazor so might miss something specific to it, but you might consider having your timer instantiate a new class that has a DbContext injected into it, passing in whatever data is needed to update the database.

    You might also look at configuring your class lifetime to be scoped. The downside is that you would hold an instance of your DbContext for each user connected to your service.