How strange... The program works perfectly in debug mode, but in release mode I get a
TypeInitializationException. Why?
The exception originates at the construction of an object (
BatchRunner) that tries to instantiate a remotable object. This remotable object is declared as a
private static variable:
#region Private Static Fields
private static RemotingWrapper Wrapper = CreateRemotingWrapper();
#endregion
And herein lies the problem. The call to
CreateRemotingWrapper() fires when the implicit static constuctor is called. In release mode the compiler makes certain optimizations that it does not make in debug mode. Apparently causing implicit static constructors to execute very, very early.
My console apps main method looks like this:
[STAThread
]static void Main
(string[] args
){ Console.
WriteLine("Reading remoting configuration."); RemotingConfiguration.
Configure( AppDomain.
CurrentDomain.
SetupInformation.
ConfigurationFile); BatchRunner batchRunner
= new BatchRunner
(); batchRunner.
Execute(); Console.
WriteLine("Program finished."); Console.
ReadLine();}
One would say that the remoting configuration is read way before the rest of the program executes. This is both true and false... True in debug mode, false in release mode

. Because the
BatchRunner contains a static field, its
implicit static constructor fires before the call to
RemotingConfiguration.Configure. This being the case,
CreateRemotingWrapper() executes without a proper remoting configuration. Consequently, the check to see if the object obtained by calling
Activator.CreateInstance(typeof(RemotingWrapper)) is a
TransparentProxy fails and throws a
RemotingException (see next code fragment).
#region Private Static Methodsprivate static RemotingWrapper CreateRemotingWrapper
(){ object remoteObject
= Activator.
CreateInstance(typeof(RemotingWrapper
)); if (!RemotingServices.
IsTransparentProxy(remoteObject
)) { throw new RemotingException
( "Could not obtain transparent proxy. Check your remoting configuration."); } else { return (RemotingWrapper
)remoteObject
; }}#endregion
Now what I don't quite understand is why the
RemotingException does not occur right at the start of my program... Why do I have to wait until the
BatchRunner is instantiated, causing a
TypeInitializationException as a result of the thrown
RemotingException?!