gpt4 book ai didi

c# - ASP.NET Core 2.0 MVC 自定义数据库初始化程序类上的 ObjectDisposedException

转载 作者:行者123 更新时间:2023-12-02 15:07:48 30 4
gpt4 key购买 nike

我在我的自定义数据库初始化程序类中遇到以下异常:

System.ObjectDisposedException occurred HResult=0x80131622
Message=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() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Source= StackTrace: at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed() at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.d__48.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.<CreateAsync>d__22.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()<br/>
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() at Microsoft.AspNetCore.Identity.UserManager1.<CreateAsync>d__73.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()<br/>
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() at Microsoft.AspNetCore.Identity.UserManager1.<CreateAsync>d__78.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() at LlabApp.Data.DbInitializer.d__4.MoveNext() in E:\C# projects\Atenea\LlabApp\LlabApp\LlabApp\Data\DbInitializer.cs:line 58

这是初始化程序:

public class DbInitializer : IDbInitializer
{
private readonly ApplicationDbContext _Context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;

public DbInitializer(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}

public async void Initialize()
{
var adminUsers = _userManager.GetUsersInRoleAsync(RoleClaimValues.Admin).Result;
if (adminUsers == null || adminUsers.Count == 0)
{
(...)
}
}
}

public interface IDbInitializer
{
void Initialize();
}

这里是 startup.cs,我在其中添加了 IDbInitializer 的范围在ConfigureService然后从 Configure 调用它:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }


public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ApplicationConnection")));

services.AddIdentity<ApplicationUser, ApplicationRole>(o => {
o.Password.RequireDigit = false;
o.Password.RequiredLength = 4;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddMvc();

// Add application services.
services.AddTransient<IEmailSender, MessageServices>();
//Seed database
services.AddScoped<IDbInitializer, DbInitializer>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbInitializer dbInitializer)
{
loggerFactory.AddConsole();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

app.UseBrowserLink();
app.UseDatabaseErrorPage();

app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");
}
else
{
app.UseExceptionHandler("/Error");
}

app.UseStaticFiles();
app.UseAuthentication();

dbInitializer.Initialize();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

我不知道为什么异常告诉我问题可能是上下文被放置在某处。

我也添加了

.UseDefaultServiceProvider(options =>
options.ValidateScopes = false)

.UseStartup<Startup>()之后以防万一它是与范围相关的东西,但异常(exception)是相同的。

最佳答案

我遇到了和你一样的问题。您确实必须更改所有代码才能返回 Task。否则,DbContext 在所有操作完成之前被释放。

数据库初始化在 dotnet core 2.0 中发生了变化。我创建了一个关于这个特定主题的博客。参见 http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/获取更多信息。

关于c# - ASP.NET Core 2.0 MVC 自定义数据库初始化程序类上的 ObjectDisposedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46131782/

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