我有一个静态连接工厂类,需要从配置中初始化连接参数namespace MyApp.Common.LinqToDB{ public static class MyConnectionFactory { public static string Authority { get; set; } public static string Target { get; set; } public static string ConnectionString { get; set; } public static string ClientId { get; set; } public static string ClientSecret { get; set; } private static ClientCredential ClientCredential = new ClientCredential(ClientId, ClientSecret); public static IDbConnection createConnection() { AuthenticationContext authenticationContext = new AuthenticationContext(Authority); AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(Target, ClientCredential).Result; SqlConnection MyDataConnection = new SqlConnection(ConnectionString); MyDataConnection.AccessToken = authenticationResult.AccessToken; return MyDataConnection; } }}从主要参数中我尝试初始化这些属性MyConnectionFactory.Authority = "blahblah";这会在静态类中引发空值异常。该值未到达班级。System.TypeInitializationException HResult=0x80131534 Message=The type initializer for 'Workspace.Common.LinqToDB.WorkspaceConnectionFactory' threw an exception. Source=Common StackTrace: at Workspace.Common.LinqToDB.WorkspaceConnectionFactory.set_Authority(String value) in ........Inner Exception 1:ArgumentNullException: Value cannot be null.Parameter name: clientId设置静态类的静态属性值是否错误?我知道静态构造函数(),但它不带参数,我需要设置连接参数。静态工厂不是连接工厂的正确模式吗?如果我不使工厂静态化,我可以使整个事情正常进行,但这似乎不是正确的做法。
1 回答
浮云间
TA贡献1829条经验 获得超4个赞
private static ClientCredential ClientCredential = new ClientCredential(ClientId, ClientSecret);将被编译为:
private static ClientCredential ClientCredential;
//Static constructor
static MyConnectionFactory()
{
ClientCredential = new ClientCredential(ClientId, ClientSecret);
}
静态构造函数用于初始化任何静态数据,或执行只需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前会自动调用它。
现在,当您尝试分配时Authority,必须先调用静态构造函数。此时,ClientId和ClientSecret仍然为空,这导致了异常。
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报
0/150
提交
取消