DBContext disposing before asynchronius method completes

Advertisements

Problem only occurs when I’m using asynchronius method.
It occurs in this line of code

await context.SaveChangesAsync();

When i change the method to synchronious everything works fine.

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.

I have the following code below:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<ForumProjectContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString")));



builder.Services.AddScoped<ILoginService, LoginService>();
builder.Services.AddScoped<IRegisterService, RegisterService>();



var app = builder.Build();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Forum/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Forum}/{action=Index}/{id?}");

app.Run();

Controller:

using Microsoft.AspNetCore.Mvc;
using Project_Fourm.Models;
using Project_Fourm.Services;

namespace Project_Fourm.Controllers
{
    public class AccountController : Controller
    {
        private readonly ForumProjectContext ProjectContext;
        private readonly IRegisterService RegisterService;


        public AccountController(IRegisterService registerService, ForumProjectContext projectContext)
        {
            RegisterService = registerService;
            this.ProjectContext = projectContext;
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index", "Forum");
            }
            else
            {
                return View(model);
            }
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                RegisterService.RegisterUser(ProjectContext, model.Username, model.Password, model.Email, model.Date);
                return RedirectToAction("Login");
            }
            else
            {
                return View(model);
            }


        }
    }
}

Service:

    using Project_Fourm.Models;
    using System.CodeDom;

    namespace Project_Fourm.Services
    {
        public class RegisterService : IRegisterService
        {
            public async Task RegisterUser(ForumProjectContext context, string username, string password, string email, DateTime date)
            {
                    User user = new User
                    {
                        Username = username,
                        Passwd = password,
                        Email = email,
                        DateOfBirth = date,
                        IsAdmin = false
                    };

                    await context.Users.AddAsync(user);
                    await context.SaveChangesAsync();


            }
        }
    }

>Solution :

You need to await the call to RegisterUser.

In order to await it, your Register action will need to become async Task<IActionResult>.

Leave a ReplyCancel reply