在MVC应用程序中设置的DB上下文可用多长时间?

时间:2021-09-19 16:57:20

I have the following in my MVC Application:

我的MVC应用程序中有以下内容:

namespace WebUx.Areas.User.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

Plus:

加:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            System.Diagnostics.Debug.Write("Set Initializer\n");
            Database.SetInitializer<UsersContext>(null);


            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            }

I understand that when there's a call to the account controller then this will set the DB context but once this is set will it stay set for my application. What about later on for other users who connect. Will the DB context always be available?

我知道当有一个帐户控制器的调用时,这将设置数据库上下文,但一旦设置它将保持为我的应用程序设置。对于其他连接的用户,稍后呢? DB上下文是否始终可用?

The reason I am asking this is that I have other information that I want to store in a table and access with Web API. Should I code in something similar for these controllers so that each time I check that there's a DB context available or could I just use this?

我问这个的原因是我有其他信息要存储在表中并使用Web API进行访问。我应该为这些控制器编写类似的代码,以便每次检查是否有可用的DB上下文,或者我可以使用它吗?

1 个解决方案

#1


1  

The connection is tightly coupled to the DbContext. As a result, the connection will only be open when your class which inherits DbContext, UsersContext in your case, retains its scope.

连接与DbContext紧密耦合。因此,只有在您的情况下继承DbContext,UsersContext的类保留其范围时,才会打开连接。

In your example, UsersContext is scoped to the using block.

在您的示例中,UsersContext的范围限定为using块。

using (var context = new UsersContext())
{
 //some actions
}

Therefore, once "some actions" are finished, the connection will close and any attempt to access lazy loading will throw an exception stating the connection is no longer available. Every time you need to access your database, you should start a new connection in my opinion. What you want to make sure is that you only make one actual trip to the database. Make sure that your query is optimized so that you do not make multiple trips to the database instead of just doing it all at once as that will affect your performance.

因此,一旦“某些操作”完成,连接将关闭,任何访问延迟加载的尝试都将引发异常,表明连接不再可用。每次你需要访问你的数据库时,你应该在我看来开始一个新的连接。您要确定的是,您只能实际访问数据库。确保您的查询已经过优化,这样您就不会多次访问数据库而不是一次性完成所有操作,因为这会影响您的性能。

Edit

As a side note, the using block breaks down into this:

作为旁注,使用块分解为:

try{
 var context = new UsersContext();
 //some actions
}finally{
 context.Dispose();
}

#1


1  

The connection is tightly coupled to the DbContext. As a result, the connection will only be open when your class which inherits DbContext, UsersContext in your case, retains its scope.

连接与DbContext紧密耦合。因此,只有在您的情况下继承DbContext,UsersContext的类保留其范围时,才会打开连接。

In your example, UsersContext is scoped to the using block.

在您的示例中,UsersContext的范围限定为using块。

using (var context = new UsersContext())
{
 //some actions
}

Therefore, once "some actions" are finished, the connection will close and any attempt to access lazy loading will throw an exception stating the connection is no longer available. Every time you need to access your database, you should start a new connection in my opinion. What you want to make sure is that you only make one actual trip to the database. Make sure that your query is optimized so that you do not make multiple trips to the database instead of just doing it all at once as that will affect your performance.

因此,一旦“某些操作”完成,连接将关闭,任何访问延迟加载的尝试都将引发异常,表明连接不再可用。每次你需要访问你的数据库时,你应该在我看来开始一个新的连接。您要确定的是,您只能实际访问数据库。确保您的查询已经过优化,这样您就不会多次访问数据库而不是一次性完成所有操作,因为这会影响您的性能。

Edit

As a side note, the using block breaks down into this:

作为旁注,使用块分解为:

try{
 var context = new UsersContext();
 //some actions
}finally{
 context.Dispose();
}