Blazor .net 8 Cannot access a disposed context instance

Mahdi Elahi 31 Reputation points
2024-01-17T20:13:27.7733333+00:00

Hi
my project is blazor .net 8 and use syncfucion data grid

but when user click on pager grid continuous (when click on pager number call service to get data by page number Capture

in repository show this error : **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: 'ApplicationDbContext'.

**
AircraftRepository.cs 297499295-163ebea9-9c84-44ca-bbe6-372857e25085 (1)

Index.Razor

<SfGrid @ref="Grid" TValue="AircraftViewModel"  AllowSorting="true" AllowFiltering="true" AllowPaging="true" RowHeight="50" Height="600">

     <SfDataManager Adaptor="Adaptors.CustomAdaptor" AdaptorInstance="@typeof(CustomAdaptor)"></SfDataManager>
   
     <GridPageSettings PageSize="25" PageSizes="@pagerDropdown" PageCount="5">
     </GridPageSettings>
                <GridColumn Field=@nameof(AircraftViewModel.Country) HeaderText="Register Number" Width="150" TextAlign="TextAlign.Center"></GridColumn>


CustomAdaptor.cs for server side rendering Data Grid

public class CustomAdaptor : DataAdaptor
{
    private readonly IAircraftService
    public CustomAdaptor(IAircraftService aircraftService)
    {
        this.aircraftService= aircraftService;
    }

    public override async Task<object> ReadAsync(DataManagerRequest dataManagerRequest, string additionalParam = null)
    {
        FilterViewModel filteringViewModel = new();

        var result = await aircraftService.GetAllAsync(filteringViewModel);

        DataResult dataResult = new DataResult
        {
            Count = result.Count,
            Result = result.Result
        };
        return dataResult;
    }
}

AircraftService.cs

 public async Task<FilterResult<AircraftViewModel>> GetAllAsync(FilterViewModel filterViewModel)
  {
      var mapped = ObjectMapper.Mapper.Map<FilterResult<AircraftViewModel>>(await aircraftRepository.GetAllAsync(filterViewModel));
      return mapped;
  }


1 .add lifetime transient :

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString), ServiceLifetime.Transient); 

**but it's not worked

**
2 . then change DBContext to AddDbContextFactory and it's not worked

 builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString), ServiceLifetime.Transient);


  1. i use await/async in all codes and methods

but i have this error , what's problem ?

Developer technologies .NET Blazor
{count} votes

3 answers

Sort by: Most helpful
  1. Mahdi Elahi 31 Reputation points
    2024-01-18T08:37:57.8566667+00:00

    @AgaveJoe
    Thanks but how to do it ? how to change my codes ? please show an example


  2. Mahdi Elahi 31 Reputation points
    2024-01-18T08:44:54.9066667+00:00

    @Bruce (SqlWork.com)
    Thanks in repository add IDisposable but it's not worked , how to solve this problem ?

     public class AircraftRepository : IAircraftRepository,IAsyncDisposable
     {
    
         private readonly ApplicationDbContext db;
         protected IQueryable<Aircraft>? query = null;
         public AircraftRepository(ApplicationDbContext db)
         {
             this.db = db;
         }
    
      public async ValueTask DisposeAsync()   {      await db.DisposeAsync();   }
    
    //My Codes
    }
    
    0 comments No comments

  3. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-01-18T17:00:23.1366667+00:00

    First I think the repository patten is bad choice with EF.

    Your repository is a wrapper (or helper class) for a dbcontext. it should NOT dispose the dbcontext, because it did not create the dbcontext. assuming you used standard DI to inject the dbcontext, the service will dispose dbcontext.

    if not using injection then its:

    using (var db = new DbContext(...))
    {
        var repository = new AircraftRepository(db); 
        ...
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.