无法访问已处置的上下文实例
Cannot access a disposed context instance
我的应用程序:使用微服务架构的 .Net Core 3.1 Web 应用程序;作为单独微服务的授权和身份验证身份 API.
我已经用自定义字段扩展了标准的 AspNetUsers 和 AspNetRoles table。
当我尝试使用 Identity RoleManager 创建新角色时出现以下错误。
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: '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)
{
}
}
管理控制器
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' 关键字。
在此处作为 'Answer' 发布,因为我无法将评论标记为 'Answer'。
我的应用程序:使用微服务架构的 .Net Core 3.1 Web 应用程序;作为单独微服务的授权和身份验证身份 API.
我已经用自定义字段扩展了标准的 AspNetUsers 和 AspNetRoles table。 当我尝试使用 Identity RoleManager 创建新角色时出现以下错误。
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: '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)
{
}
}
管理控制器
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' 关键字。 在此处作为 'Answer' 发布,因为我无法将评论标记为 'Answer'。