最近,我在使用 .NET 3.5 开发的应用程序之一中观察到以下有趣的场景。在这个特别的应用程序中,我有一个单独的对象,我将其作为静态变量访问。我预计 .NET 运行时应该在我第一次访问它时初始化这个单例对象,但似乎情况并非如此。.NET 运行时在我访问这个特定对象之前对其进行初始化。以下是一些伪代码,
if(!initSingleton)
//Do some work without using the singletion class.
else
//Do some work using the singletion class.
即使在运行时,我的代码也只执行 if 语句中的代码。NET 运行时仍然初始化单例对象。在某些应用程序运行中,我根本不需要访问这个特殊对象!
此外,我在调试版本中看不到这种行为。似乎这与优化构建(发布构建)有关。
这是 .NET 运行时的预期行为吗?
更新:
以下是实际代码,
private void InitServiceClient(NetworkCredential credentials, bool https)
{
string uri = currentCrawlingWebUrl;
if (!uri.EndsWith("/"))
uri = string.Concat(uri, "/");
uri = string.Concat(uri, siteDataEndPointSuffix);
siteDataService = new SiteData.SiteDataSoapClient();
siteDataService.Endpoint.Address = new EndpointAddress(uri);
if (credentials != null)
{
siteDataService.ClientCredentials.Windows.ClientCredential = credentials;
}
else if (MOSSStateHandler.Instance.UserName.Length > 0 && MOSSStateHandler.Instance.Password.Length > 0)
{
siteDataService.ClientCredentials.Windows.ClientCredential.UserName = MOSSStateHandler.Instance.UserName;
siteDataService.ClientCredentials.Windows.ClientCredential.Password = MOSSStateHandler.Instance.Password;
siteDataService.ClientCredentials.Windows.ClientCredential.Domain = MOSSStateHandler.Instance.Domain;
}
BasicHttpBinding httpBinding = (BasicHttpBinding)siteDataService.Endpoint.Binding;
httpBinding.Security.Mode = (https ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
string authmode = MOSSConnectorConfiguration.Instance.Config.GetString(ConfigConstants.SHAREPOINT_AUTH_PROVIDER, "ntlm");
if (authmode.Equals("ntlm", StringComparison.OrdinalIgnoreCase))
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
else if (authmode.Equals("kerberos", StringComparison.OrdinalIgnoreCase))
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
else
throw new Exception(string.Format("Not supported"));
}
即使我的应用程序不执行 else if 阻止类 MOSSStateHandler 初始化的代码。