Dispose ApplicationDbContext in ASP.NET Core

c# entity-framework-core


I have a web application and host it in Azure but the problem is that the SQL pool gets full fast regardless of tier. I was thinking that maybe I need to dispose ApplicationDbContext, is this required? would this help?

The following is a part of my class with the method Index utilizing most of SQL time:

private readonly ApplicationDbContext _context;
private readonly IEmailSender _emailSender;

public MessagesController(ApplicationDbContext context, IEmailSender emailSender)
    _context = context;
    _emailSender = emailSender;

// GET: Message
public async Task<IActionResult> Index()
    var user = _context.Users.Where(u => u.Email.Equals(User.Identity.Name)).Select(u =>
    new { u.Name, u.Subdomain, u.PhotoURL }).FirstOrDefault();
    ViewData["Name"] = user.Name;
    ViewData["Subdomain"] = user.Subdomain;
    ViewData["PhotoURL"] = (user.PhotoURL == null) ? "../../img/avatar.png" : user.PhotoURL;
    List<Message> messages = await _context.Messages.Where(m => m.UserName.Equals(User.Identity.Name))
    .Select(m => new Message { ID = m.ID, DateTime = m.DateTime, Text = m.Text }).ToListAsync();
    return View(messages);

Should I call _context.dispose() although I'm using the same context in other ActionResult methods?

5/2/2019 3:26:06 PM

Accepted Answer

No, you don't have to call _context.dispose() - the IoC container will release resources based on the lifetime setting which was used while registering them.

What is more, you wrote that "I'm using the same context in other ActionResult methods?". That's not true - well at least it shouldn't be true. The context should be created per request. So that while calling each of the controller actions your are generating new request and container is creating new context to be injected (each time when new request is done the controller is created once again).

Here is how you should register your context:

services.AddDbContext<SchoolContext>(options => options.UseSqlServer(CONNECTION_STRING));

By this you are using default lifetime for DbContext - scoped.

1/26/2017 12:23:49 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow