1

I have a wbe app mvc c#4.0, I want to Initialize DefaultRoleProvider connectionstring from code at runtime (don't want it from web.config). I created a class 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.  
        ??
    }  
}  
4

1 回答 1

0

再想一想,你可以尝试一些基于反射的东西,像这样:

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);
    }  
} 

希望这会有所帮助

于 2013-02-21T20:51:07.467 回答