Recently I have observed the following interesting scenario in one of the application I'm developing using .NET 3.5. In this particualr application I have a singletion object which I access as a static variable. I exepected that the .NET run time should initializes this singleton object at the very first time I access it, but it seems this is not the case. .NET runtime initialize it way before I access this particualr object. Following is some peudo code,
if(!initSingleton)
//Do some work without using the singletion class.
else
//Do some work using the singletion class.
Even at runtime my code only executes the code in side the if statement .NET runtime still initializes the singleton object. In some of the application runs I don't need to access this pariticualr object at all!
Also I don't see this behavior with debug builds. Seems this has something to do with optimized builds (release builds).
Is this is the expected behavior of the .NET runtime?
Update:
Following is the actual code,
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"));
}
Even though my application doesn't execute the code in side else if block the class MOSSStateHandler get initialized.