user1595443
user1595443

Reputation: 227

Cannot access a disposed object in Blazor Server 3.0

I got a Blazor page with following form submit button

<button type="submit" class="btn btn-primary" @onclick="@(async()=> await OnCreateItem())">Create </button>

Which calls

protected async Task OnCreateItem()
{
    try
    {

        var result = await dbMgr.CreateAsync(item);
    }
    catch (Exception ex)
    {
         Throws ==> 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()...
    }
}

dbMgr is injected to the page

@inject DBManager dbMgr;

And manager is implemented as

class DBManager 
{
...
    public DBManager(DBContext db)
    {
         _db = db;
    }

    public async Task<int> CreateAsync(ItemModel obj)
    {
        await _db.AddAsync(obj);
        return await _db.SaveChangesAsync()
    }
}

Startup class is

public void ConfigureServices(IServiceCollection services)
{
       services.AddRazorPages();
       services.AddServerSideBlazor();
       services.AddDbContext<DBContext >(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DBContext")),  ServiceLifetime.Scoped);
       services.AddScoped<DBManager>();
 }

I read a similar questions here Link 1 Link 2

To no avail.

Not sure what am I doing wrong.

Upvotes: 3

Views: 7590

Answers (1)

enet
enet

Reputation: 45664

I did not try your code, but I guess it is due to setting type="submit" in

<button type="submit" class="btn btn-primary" @onclick="@(async()=> await OnCreateItem())">Create </button>

As a result, when you hit the "Create" button, a traditional post back takes place. .. that is, your SPA app post back to the server. It shouldn't happen (in that case), as your app redirects to a uri outside of the limiting base uri, and then returns back, sadly enough to find the objects in the OnCreateItem dead (disposed). Just set type="button".

Important: As far as I recall from days bygone, there should be code in Blazor JavaScript to prevent such incidents: that is posting back to the server.

Upvotes: 4

Related Questions