DbContextScope icon indicating copy to clipboard operation
DbContextScope copied to clipboard

DbContext disposed if Service function called twice

Open goBazinga opened this issue 7 years ago • 3 comments

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?

goBazinga avatar Oct 06 '16 00:10 goBazinga

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.

markphillips100 avatar Nov 11 '16 00:11 markphillips100

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."

bacvothanh avatar Oct 15 '17 08:10 bacvothanh

so, register your DbContext with Transient Lifetime. See my expanded answer in this thread: https://github.com/mehdime/DbContextScope/issues/51

rock-walker avatar Dec 21 '17 21:12 rock-walker