I use GraphQL library HotChocolate.
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<ProductQuery>();
builder.Services.AddDbContext<DpcDatabaseContext>();
// ...
var app = builder.Build();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGraphQL();
app.Run();
I got my context using constructor injection:
public DpcProductDatabaseService(DpcDatabaseContext dpcDatabaseContext)
{
_dpcDatabaseContext = dpcDatabaseContext;
}
And how I get products:
var res = await _dpcDatabaseContext.Products.FirstOrDefaultAsync(z => z.Id == 1, cancellationToken);
And what I get:
System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it 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: 'DpcDatabaseContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, LambdaExpression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
at DpcMicroService.Services.DpcProductDatabaseService.GetProductsByFilterFromDbInternalAsync(FilterInput filter, DpcDatabaseContextBase ctx, CancellationToken cancellationToken) in C:\Beeline\DpcMicroService\DpcMicroService\DpcMicroService\Services\DpcProductDatabaseService.cs:line 86
Where Im I wrong? If I create my context manually using new it works. But this is not a way out for me. Please, helpme to figure out what is wrong.
I also tried to configure DI in this way:
builder.Services.AddDbContext<DpcDatabaseContext>(ServiceLifetime.Transient);
It did not have any effect.