我的 MVC 应用程序中有以下内容:
namespace WebUx.Areas.User.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
加:
[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);
}
我知道当调用帐户控制器时,这将设置数据库上下文,但是一旦设置,它将为我的应用程序保持设置。稍后连接的其他用户呢?数据库上下文是否始终可用?
我问这个的原因是我有其他信息要存储在表中并使用 Web API 访问。我应该为这些控制器编写类似的代码,以便每次检查是否有可用的数据库上下文,还是可以只使用它?