gpt4 book ai didi

c# - 无法访问已处置的上下文实例

转载 作者:行者123 更新时间:2023-12-04 08:24:06 26 4
gpt4 key购买 nike

我的应用:.Net Core 3.1 Web 应用,采用微服务架构;用于授权和身份验证的身份作为单独的微服务 API。
我已经使用自定义字段扩展了标准的 AspNetUsers 和 AspNetRoles 表。
当我尝试使用 Identity RoleManager 创建新角色时出现以下错误。

Cannot access a disposed context instance. A common cause of thiserror is disposing a context instance that was resolved fromdependency injection and then later trying to use the same contextinstance elsewhere in your application. This may occur if you arecalling 'Dispose' on the context instance, or wrapping it in a usingstatement. If you are using dependency injection, you should let thedependency injection container take care of disposing contextinstances. Object name: 'MembershipDBContext'.


在下面找到我的代码
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var idenConnectionString = Configuration["DbContextSettings:IdentityConnectionString"];
var userConnectionString = Configuration["DbContextSettings:UserConnectionString"];
var dbPassword = Configuration["DbContextSettings:DbPassword"];
var builder = new NpgsqlConnectionStringBuilder(idenConnectionString)
{
Password = dbPassword
};
var userBuilder = new NpgsqlConnectionStringBuilder(userConnectionString)
{
Password = dbPassword
};

services.AddDbContext<MembershipDBContext>(opts => opts.UseNpgsql(builder.ConnectionString));
services.AddDbContext<UserDBContext>(opts => opts.UseNpgsql(userBuilder.ConnectionString));



services.AddIdentity<MembershipUser, MembershipRole>(options =>
{
options.Password.RequiredLength = 8;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
options.SignIn.RequireConfirmedEmail = false;
}).AddRoles<MembershipRole>().AddEntityFrameworkStores<MembershipDBContext>()
.AddDefaultTokenProviders();


services.AddTransient<IIdentityMSService, IdentityMSService>();//IdentityMS
services.AddTransient<IAdministrationService, AdministrationService>();//IdentityMS

services.AddTransient<IIdentityMSRepository, IdentityMSRepository>();//IdentityMS
services.AddTransient<IAdministrationRepository, AdministrationRepository>();//IdentityMS
services.AddTransient<UserDBContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

services.AddMediatR(typeof(Startup));
RegisterServices(services);
}
MembershipDBContext.cs
    public class MembershipDBContext : IdentityDbContext<MembershipUser,MembershipRole,string>
{
public MembershipDBContext(DbContextOptions<MembershipDBContext> options) : base(options)
{
}
}
管理 Controller
 public class AdministrationController : Controller
{
private readonly IAdministrationMVCService _adminService;

public AdministrationController(IAdministrationMVCService adminService)
{
_adminService = adminService;
}

// GET: AdministrationController/Create
public ActionResult Create()
{
return View();
}

// POST: AdministrationController/Create
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateAsync(MembershipRole rm)
{
if (ModelState.IsValid)
{
try
{
rm.CompanyId = 1;
await _adminService.AddRoles(rm);
//return RedirectToAction(nameof(Index));
return View();
}
catch
{
return View();
}
}
return View();
}


}
AdministrationApiController
[HttpPost]
public void Post([FromBody] MembershipRole role)
{
_adminMSService.AddRoles(role);
}
AdministrationRepository
public class AdministrationRepository : IAdministrationRepository
{
private readonly RoleManager<MembershipRole> _roleManager;
private readonly UserManager<MembershipUser> _userManager;

public AdministrationRepository(RoleManager<MembershipRole> roleManager, UserManager<MembershipUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}

public async Task AddRolesAsync(MembershipRole rvm)
{
try
{
IdentityResult result = await _roleManager.CreateAsync(rvm);
if (result.Succeeded) {

}
}
catch (Exception ex)
{
throw;
}
}

}
我尝试将服务和存储库设为 单例 但它也不起作用。我在这里缺少什么?任何见解?

最佳答案

解决了问题!正如 DavidG 在评论中指出的那样,我在 AdministrationApiController 等某些地方错过了“await”关键字。
在这里发布为“答案”,因为我无法将评论标记为“答案”。

关于c# - 无法访问已处置的上下文实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65356290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com