Azure / Azure/azure-functions-dotnet-extensions
Problem with referencing one scoped service in another
- Dominant language
- C#
- Stars
- 81
- Forks
- 50
- PR merge metrics
- No merged PRs in 30d
Description
I have a Entity framework DatabaseContext that I like to add also as my DatabaseContextBase.
DatabaseContext inherits from DatabaseContextBase and DatabaseContextBase inherits from DbContext.
Here is how I've tried it:
In startup:
```
services.AddDbContext(options =>...);
services.AddScoped(sp => sp.GetRequiredService());
services.AddScoped();
services.AddScoped();
```
Then in the function I use those 2:
```
SomethingThatUsesDatabaseContext.DoSomething();
SomethingThatUsesDatabaseContextBase.DoSomethingElse();
```
The first one works fine but the second one fails with this exception:
> System.ObjectDisposedException
> HResult=0x80131622
> Message=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.
> Object name: 'DatabaseContext'.
> Source=Microsoft.EntityFrameworkCore
> StackTrace:
> at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
> at Microsoft.EntityFrameworkCore.DbContext.AddRangeAsync(Object[] entities)
> at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.AddRangeAsync(TEntity[] entities)
> at SomethingThatUsesDatabaseContextBase
> .d__6.MoveNext() in
>
Contributor guide
No contributing guide indexed for this repository
Research direction
Start by reproducing the service registrations shown in Startup and trace how DatabaseContext and DatabaseContextBase are resolved by SomethingThatUsesDatabaseContext and SomethingThatUsesDatabaseContextBase. Confirm the lifetime and disposal behavior around AddDbContext, then document a minimal reproduction or test showing the failing call and define done as both services using the context without ObjectDisposedException.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100