我正在创建一个多层次的ASP.NET MVC网站。
是否有建议的方法来处理这些对象的初始创建?以下是我看到的选项:
这里的标准方法是什么?
答案 0 :(得分:0)
所以这就是我使用SimpleMembershipProvider
解决这个问题的方法,如果它们足够相似,也许您可以根据需要轻松调整此代码:
[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()
{
Database.SetInitializer<MyDbContext>(null);
try
{
using (var context = new MyDbContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DAL.MyDbContext", "UserProfiles", "UserId", "UserName", autoCreateTables: true);
if (!Roles.RoleExists("SuperAdmin"))
{
Roles.CreateRole("SuperAdmin");
WebSecurity.CreateUserAndAccount("SuperAdmin", "12345");
Roles.AddUsersToRole(new[] { "SuperAdmin" }, "SuperAdmin");
}
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
这是我在文件夹Filters
中的主项目。然后在Global.asax.cs
:
protected void Application_Start()
{
//All the other stuff..
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}