在ASP.NET Core中配置ApplicationDbContext

时间:2017-01-26 00:34:21

标签: c# entity-framework-core

我有一个Web应用程序并在Azure中托管它,但问题是SQL池无论层级如何都快速完全填满。 我在想,也许我需要处理ApplicationDbContext,这需要吗?这会有帮助吗?

以下是我的类的一部分,使用方法Index利用大部分SQL时间:

private readonly ApplicationDbContext _context;
private readonly IEmailSender _emailSender;

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

// GET: Message
[Authorize]
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);
}

我是否应该调用_context.dispose(),尽管我在其他ActionResult方法中使用相同的上下文?

1 个答案:

答案 0 :(得分:1)

不,您不必调用_context.dispose() - IoC容器将根据注册时使用的生命周期设置释放资源。

更重要的是,您写道“我在其他ActionResult方法中使用相同的上下文?”。这不是真的 - 至少它不应该是真的。应根据请求创建上下文。因此,在调用每个控制器操作时,您正在生成新请求,容器正在创建要注入的新上下文(每次完成新请求时,控制器都会再次创建)。

以下是注册背景的方法:

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

这样你就可以使用DbContext的默认生命周期 - 作用域。

相关问题