我有一个wbe app mvc c#4.0,我想在运行时从代码初始化DefaultRoleProvider connectionstring(不希望它来自web.config)。 我创建了一个MyRoleProvider类:DefaultRoleProvider
public class MyRoleProvider : DefaultRoleProvider
{
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
// Update the private connection string field in the base class.
bool IsLocal = bool.Parse(ConfigurationManager.AppSettings["IsLocal"] as string);
string connectionString = "local connectionString ... ";
if (IsLocal == false)
connectionString = "prod connectionString ...";
//ToDo- how to set connection string next property of provider.
??
}
}
答案 0 :(得分:0)
第二个想法,你可以尝试基于Reflection的东西,像这样:
public class CustomRoleProvider : SqlRoleProvider
{
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
// Update the private connection string field in the base class.
bool IsLocal = bool.Parse(ConfigurationManager.AppSettings["IsLocal"] as string);
string connectionString = "local connectionString ... ";
if (!IsLocal)
{
connectionString = "prod connectionString ...";
System.Reflection.FieldInfo field;
field = this.GetType()
.GetField("_sqlConnectionString",
System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.NonPublic);
field.SetValue(this, connectionString);
}
}
-------------------- 首发
我担心这样做的最好方法是动态选择连接字符串名称,并引用已在web.config中声明的另一个连接。像这样的类扩展SqlRoleProvider
:
public class CustomRoleProvider : SqlRoleProvider
{
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
bool IsLocal = bool.Parse(ConfigurationManager.AppSettings["IsLocal"] as string);
string connectionStringName = "local connectionString name ";
if (!IsLocal)
connectionStringName = "prod connectionString name";
config.Set("connectionStringName", connectionStringName );
base.Initialize(name, config);
}
}
希望这会有所帮助