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 disposed if Service function called twice #45

Open
goBazinga opened this issue Oct 6, 2016 · 3 comments
Open

DbContext disposed if Service function called twice #45

goBazinga opened this issue Oct 6, 2016 · 3 comments

Comments

@goBazinga
Copy link

goBazinga commented Oct 6, 2016

I have a generic repository pattern implemented where I set my dbcontext from ambientDbContextLocator. In my service I have using block for dbcontextScopeFactory where repository is used for query.

using (var dbContextScope = _dbContextScopeFactory.Create())
{
_peopleRepository.Table.Where(x => x.Id == id);
}

calling this service function once is fine, but second call says DbContext has been disposed. Tried usign CreateReadOnly as well but no luck. Am I doing something wrong here?

@markphillips100
Copy link

markphillips100 commented Nov 11, 2016

I'm assuming your _dbContextScopeFactory is injected via an IoC. If your container supports it (AutoFac does) you can inject a Func<IDbContextScopeFactory> dbContextScopeFactoryFunc and change your using statement to the following:

using (var scope = _dbContextScopeFactory().Create()) { ...repo stuff scope.SaveChanges(); }

You can repeat as many using statements in the same code, each will commit separately to the db. Not sure how this behaves for nested ambient repository calls though.

@bacvothanh
Copy link

I had same issue right here, when try to call service in second time, the DbContext will throw an exception "The operation cannot be completed because the DbContext has been disposed."

@rock-walker
Copy link

so, register your DbContext with Transient Lifetime.
See my expanded answer in this thread: #51

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

4 participants