ASP.NET MVC 4 and dynamically changing membership connection string with CodeFirst

怎甘沉沦 提交于 2020-01-01 19:28:40

问题


I am working on creating a MVC4 multi-tenant site that uses seperate DBs for each tenant and have been trying to get the membership piece to work for each tenant without any luck.

For some reason connectionStringField is always null no matter what I do. Any ideas why this could happen?

public class CodeFirstMembershipProvider : MembershipProvider
    {    
      public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)  
      { 
          base.Initialize(name, config);  

          // hard coded for testing  
          string connectionString = @"server=localhost;database=masterdb;uid=master;pwd=password";

          // Set private property of Membership provider.  
          FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);  
          if(connectionStringField != null)
            connectionStringField.SetValue(this, connectionString);  
      }
}

回答1:


You can't make this work. Even if you could figure out how to get the reflection to function the way you want. It will lead to instability and unexpected results.

The reason is that the Membership Provider is a global static, single instance that is used across all concurrent users. That means if you change the connection string for one user, it changes it for all of them. Worse, you might change it for one, then have a context switch to another user and they might overwrite that change, then come back and the app isn't in a state that it thinks it's in.

The built-in Membership system is not designed to have it's internal data changed while it is running. It's designed to use a single database for multiple applications.

If you insist on using separate databases for each tenant, then you will have to implement your own authentication system, because Membership simply will not work in the situation you want it to. It may appear to work at first, but as your site gains more concurrent users, it's a ticking time bomb waiting to blow up in your face.



来源:https://stackoverflow.com/questions/12924933/asp-net-mvc-4-and-dynamically-changing-membership-connection-string-with-codefir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!