I have implemented a base controller that instantiates a new DbContext
per request:
public class BaseController: Controller
{
protected HawkHeadDbContext Db { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Db = new HawkHeadDbContext();
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
Db.SaveChanges();
Db.Dispose();
}
}
I am just a little worried that the Dispose
call could become CPU intensive, and maybe I should dispose the context in the Dispose
method of BaseController
. I suspect the controller is instantiated for each request, but not sure if Dispose
is called after each request, or in a regular 'DisposeAllControllers' type operation.
The context is designed for short time lifetime. Usually you see it in
using(var ctx = new DbContext())
{
...
}
Which means ctx.Dispose is called just after end of use.
More details here , see "lifetime" section.
So regarding your code, if you aren't using dependency injection (In which case you would have configured dbcontext as per request) you are doing well disposing it after action execution.
The only concern would be what if you call child actions.. In that case you may end having more than one dbcontext per request
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.