Skip to content
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

Closed
derth opened this issue Nov 15, 2018 · 4 comments
Closed

dbcontext in IHostedService #9596

derth opened this issue Nov 15, 2018 · 4 comments
Milestone

Comments

@derth
Copy link

derth commented Nov 15, 2018

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.

@guardrex
Copy link
Collaborator

Hello @derth ... Did you try creating a scope for your scoped dbcontext? ...

https://docs.microsoft.com/aspnet/core/fundamentals/host/hosted-services#consuming-a-scoped-service-in-a-background-task

@guardrex guardrex added this to the Backlog milestone Nov 15, 2018
@guardrex guardrex added the P4 label Nov 15, 2018
@derth
Copy link
Author

derth commented Nov 16, 2018

[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):

internal class ScopedProcessingService : IScopedProcessingService
{
    public ScopedProcessingService(myService myService)
    {
        _myService = myService;
    }

    public async Task DoWork()
    {
        // _myService uses dbContext
        await _myService.Test();
    }
}

internal class ConsumeScopedServiceHostedService : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        using (var scope = Services.CreateScope())
        {
            // if running asynchronous it doesn't work
            var scopedProcessingService = scope.ServiceProvider.GetRequiredService<IScopedProcessingService>();
            scopedProcessingService.DoWork();

            //// if running synchronous it works
            //var ApplicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            //var entries = ApplicationDbContext.xxx.ToList();
        }

        return Task.CompletedTask;
    }
}

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?

@guardrex
Copy link
Collaborator

@Tratcher Can you assist?

@Tratcher
Copy link
Member

Tratcher commented Nov 16, 2018

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.

@derth derth closed this as completed Nov 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants