当使用依赖注入注入DbContext时,需要在Startup.cs中对DbContext进行Scoped注入,使其在每个请求或操作中都使用不同的实例。例如:
在Startup.cs中加入以下代码:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString")),
ServiceLifetime.Scoped);
其中,ServiceLifetime.Scoped表示为每个请求创建一个新的DbContext实例。
另外,需要注意在使用完DbContext后,要手动调用Dispose()方法释放它所占用的资源,避免出现对象已被释放的异常。