Question

I am generating my own proxy that wraps objects returned from MongoDB. The proxy implements an interface:

interface IProxy
{
    string __ID {get;}
}

The Proxy Generator uses the following code to generate the implementation

PropertyBuilder proxyID = typeBuilder.DefineProperty("__ID", PropertyAttributes.None, typeof(string), null);
proxyID.SetCustomAttribute(new CustomAttributeBuilder(typeof(Root.Attributes.DataAnnotations.NotMappedAttribute).GetConstructor(Type.EmptyTypes), new object[0]));
 MethodBuilder proxyID_PropertyGet = typeBuilder.DefineMethod("get___ID", MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(string), Type.EmptyTypes);
 ILGenerator __IDILget = proxyID_PropertyGet.GetILGenerator();
 __IDILget.Emit(OpCodes.Ldarg_0);
 __IDILget.Emit(OpCodes.Ldfld, objectID);
 __IDILget.Emit(OpCodes.Callvirt, typeof(ObjectId).GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance));
 __IDILget.Emit(OpCodes.Ret);
 proxyID.SetGetMethod(proxyID_PropertyGet);

The application is compiled with the "Any CPU" configuration.

When running on our development machines using the Visual Studio web server, the application works fine.

When running on IIS7.5 (Windows 2008 R2), it throws an invalid program exception whenever the __ID property is accessed. Changing the "Enable 32-bit applications" setting to true changes this behavior.

I'd like to not have to modify the IIS configuration. Why does the exception only get thrown in 64-bit applications?

Was it helpful?

Solution

It turns out that the field ToString() is called on is a struct, so the IL had to change to:

ILGenerator __IDILget = proxyID_PropertyGet.GetILGenerator();
__IDILget.Emit(OpCodes.Ldarg_0);
__IDILget.Emit(OpCodes.Ldflda, objectID);
__IDILget.Emit(OpCodes.Constrained, typeof(ObjectId));
__IDILget.Emit(OpCodes.Callvirt, typeof(ObjectId).GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance));
__IDILget.Emit(OpCodes.Ret);
proxyID.SetGetMethod(proxyID_PropertyGet);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top