代码之家  ›  专栏  ›  技术社区  ›  Anon2391

在异步方法完成之前处理DBContext

  •  -1
  • Anon2391  · 技术社区  · 1 年前

    只有当我使用异步方法时才会出现问题。

    它出现在这行代码中

    await context.SaveChangesAsync();
    

    当我将方法更改为同步时,一切都很好。

    错误:

    无法访问已释放的上下文实例。导致此错误的一个常见原因是处理通过依赖项注入解决的上下文实例,然后尝试在应用程序的其他地方使用相同的上下文实例。如果对上下文实例调用“Dispose”,或将其包装在using语句中,则可能会发生这种情况。如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。

    我有以下代码:

    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();
    

    控制器:

    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);
                }
            }
        }
    }
    

    服务:

        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();
                }
            }
        }
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   Stephen Cleary    1 年前

    你需要 await 呼叫 RegisterUser

    为了 等候 它,你的 Register 行动将需要 async Task<IActionResult>