看到大家使用DBContext都是
using(var test=new DBContext())
{
//Doing
}
当我一个action里面需要访问多个模块。每个模块都需要访问数据库。这样就需要using和new DBContext很多次。
那么我能否在OnActionExecuting 中new DBContext,然后再OnActionExecuted 或者OnResultExecuted 再进行DBContext.Dispose()呢???
看到大家使用DBContext都是
using(var test=new DBContext())
{
//Doing
}
当我一个action里面需要访问多个模块。每个模块都需要访问数据库。这样就需要using和new DBContext很多次。
那么我能否在OnActionExecuting 中new DBContext,然后再OnActionExecuted 或者OnResultExecuted 再进行DBContext.Dispose()呢???
以下回答参考 皆我百晓生、券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。
可以的,你可以根据你的需求来决定是否要在OnActionExecuting方法中调用using语句,并且在相应的OnActionExecuted或OnResultExecuted方法中调用Dispose()来释放资源。
例如:
public class MyController : Controller
{
public ActionResult Index()
{
using (var db = new MyDbContext())
{
// Do something with the database context here.
}
return View();
}
}
public class MyDbContext
{
// Your database context implementation goes here.
}
在这个例子中,当Index方法执行时,它会创建一个新的MyDbContext实例并将其传递给using语句。然后,任何操作都在这个新的上下文中进行。当你完成操作后,你只需要在OnActionExecuted方法中调用db.Dispose()即可释放资源。
注意:这种方法可能会导致一些内存泄漏问题,因为每次调用using都会创建一个新的上下文实例。如果你希望避免这种情况,可以考虑使用托管对象(Managed Object Model, MEF)或者其他技术来管理上下文实例。