views:

56

answers:

2

I have a rather convoluted scenario where I want to create a DynamicMethod that's attached to a class in an in-memory AssemblyBuilder. The dynamic method calls a method "GetReplacement" in a (regular) assembly of mine.

This worked fine in .NET 2.0, but in .NET 4.0 I get an error:

MethodAccessException: Attempt by security transparent method 'DynamicClass.Max(Int32, Int32)' 
to access security critical method 'xxx.GetReplacement()' failed.

From what I've read, my dynamic method (Max in the error above) is security-transparent because the assembly it's attached to (the AssemblyBuilder) is transparent. I'm guessing the AssemblyBuilder is transparent because it's a dynamic assembly.

How do I make my dynamic method critical or do whatever it takes to grant it permission to call GetReplacement? There are a couple of other methods I want to call in GetReplacement's assembly so fixing the dynamic method would be better than marking GetReplacement in some way.

I'm a bit lost and would love some help!

+1  A: 

While creating the AssemblyBuilder you should use a CustomAttributeBuilder to assign a SecurityCriticalAttribute to the assembly.

Once the assembly is marked a Security-Critical you could add the same attribute to any DynamicMethod.

CriGoT
A: 

Oops, this was a mistake on my part. The docs are right: the dynamic method inherits its security from the type to which it's attached. Methods that you don't attach to a type are attached to a security transparent assembly. You can't add an attribute to a DynamicMethod overriding the security -- you have to attach it to an appropriate type.

I was making a dumb mistake: looking at the dynamic method attached to an AssemblyBuilder, not the one attached to mscorlib (which is security transparent).

mcobrien