我有一个包含数百个静态方法和变量的类库,如下所示...
public class General
{
public static string Con { get; set; }
public static string Func1()
{
using (SqlConnection con = new SqlConnection(Con))
{
// My stuff here
}
}
public static string Func2()
{
using (SqlConnection con = new SqlConnection(Con))
{
// My stuff here
}
}
public static string Funcn()
{
using (SqlConnection con = new SqlConnection(Con))
{
// My stuff here
}
}
}
我将此类库引用到我的 ASP.Net Webform 应用程序,并从 Global.asax 的 Application_Start 事件分配连接字符串
protected void Application_Start(object sender, EventArgs e)
{
General.Con = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
}
一切正常。
现在我想按用户登录更改数据库连接字符串。
我尝试过的:
我将所有用户的连接字符串信息存储在公共数据库的一个表中,并将它们映射到各自的用户 ID。
单击登录按钮时,我可以将连接字符串保存到会话。
Session["Con"] = ds.Tables[0].Rows[0][0].ToString();
在我使用的类库中
Public static string Con = System.Web.HttpContext.Current.Session["Con"].ToString();
我收到错误:对象引用未设置为对象的实例。 如果我删除静态,我所有的变量和方法都会给出一个错误:非静态需要对象引用 如果我在这里使用 new 关键字,错误是"无法使用实例引用访问;改用类型名称限定它"。
然后我用了
public static string Con()
{
string Con = "";
HttpContext httpContext = HttpContext.Current;
if (httpContext.ApplicationInstance.Session.Count > 0)
{
if (httpContext.ApplicationInstance.Session["Con"] != null)
Consd = httpContext.ApplicationInstance.Session["Con"].ToString();
}
return Con;
}
它给我错误:无法从方法组转换为字符串
请帮帮我...
您的类是静态的,这意味着只有一个实例,但您希望基于用户更改连接。
这显然是行不通的。我个人建议您允许类的多个实例(非静态),并使用连接字符串作为参数初始化每个实例:
public class General
{
private string _connectionString;
public General(string connectionString)
{
_connectionString = connectionString;
}
}
然后,如果需要,您可以为每个会话实例化一次,或者每次需要使用它时都实例化它。我不建议将依赖项添加到类中(例如,连接字符串的来源)。
var data = new General(ds.Tables[0].Rows[0][0].ToString());
var result = data.Func1();
如果由于某种原因需要保持类静态,则需要向函数提供连接字符串,以便它可以使用它,或者嵌入逻辑以将连接字符串从会话中提取到方法中:
public static string Func1(string connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
// My stuff here
}
}
或
public static string Func1()
{
using (SqlConnection con = new SqlConnection(ds.Tables[0].Rows[0][0].ToString()))
{
// My stuff here
}
}
如果您决定采用此路线,我建议您将连接字符串作为参数传递。
如果您希望保持类静态,最后一个选项是使用提供连接字符串的 Configurator 对象,以便抽象位置:
public interface IConfigurator
{
string GetConnectionString();
}
public class SessionConfigurator : IConfigurator
{
public string GetConnectionString()
{
var connectionString = Session["Con"].ToString();
return connectionString;
}
}
public static class General
{
public IConfigurator Configurator { get; set; }
public static string Func1()
{
using (SqlConnection con = new SqlConnection(Configurator.GetConnectionString()))
{
// My stuff here
}
}
}
然后在应用程序启动时:
General.Configurator = new SessionConfigurator();