-
Notifications
You must be signed in to change notification settings - Fork 25.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
dbcontext in IHostedService #9596
Comments
Hello @derth ... Did you try creating a scope for your scoped dbcontext? ... |
[EDIT] I'm adding triple backticks (```) above and below the code snippet to make this render as a code block. This is the code i have (removed unimportant code):
From what i see, since my DoWork() method is asynchronous, it returns and exits the scope, and when it tries to resolve the dbcontext it throws the error. Is there a code example for when the ScopedProcessingService.DoWork() is an async method? |
@Tratcher Can you assist? |
await the call to DoWork, otherwise scope and scoped services get disposed. If you're trying to avoid blocking StartAsync then do something like a Task.Run before creating the scope. |
How can i use the dbcontext in IHostedService?
If i just resolve my service and try to use it, when it tries to use the dbcontext, i get the following exception:
"Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.\r\nObject name: 'AsyncDisposer'."
Do i have to resolve the dbContext too, and if so, can i inject it into the scoped context and continue using di or i have to pass the reference manually to all the methods that use it?
It would be nice if docs had an example for how to use dbContext.
The text was updated successfully, but these errors were encountered: