Question

I have a webservice in a certain namespace, let's call it MyNamespace. It's a normal webservice with webmethods in the code behind. I also have an additional .cs file with all kinds of classes used in those webmethods. So far so good, right?

Then I have an additional webservice used for testing stuff only. It has no code behind and its code is directly in the .asmx file so I can quickly upload it to a server without rebuilding anything. This test webservice is in the same MyNamespace namespace as the webservice mentioned in the first paragraph and in the same project as well. It works great and all until I try to access internal members of MyNamespace. It cannot be done, they are invisible, as if they were private.

This is the point where I might start to write nonsense, so please correct me if necessary. I have looked around a bit and it seems this is 'intended' because an .asmx without a proper code behind is compiled at runtime and is not a part of a proper assembly. Since internal members are available only within the assembly, it's entirely correct for them to be not available in my .asmx code. My question then is - can I access these members somehow without moving my code to a .asmx.cs code behind file?

Was it helpful?

Solution

I would imagine this is possible using reflection.

For example: To invoke an internal method on a public class:

var myPublicClass = new PublicClass;
MethodInfo mInfo = typeof(PublicClass).GetMethod("InternalMethodName", BindingFlags.Instance | BindingFlags.NonPublic);

var result = mInfo.Invoke(myPublicCLass, null) // (replace null with an array of parameters if necessary)

Or to create in instance of a internal class:

MethodInfo mInfo= Type.GetType(assemblyQualifiedName).GetConstructor(
                        BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        new[] { typeof(string) },
                        null
                    );
object myInstance = mInfo.Invoke(new[] { "constructorArgument" });

Edit: Internal static method on internal static class:

MethodInfo mInfo = Type.GetType(assemblyQualifiedName).GetMethod("InternalMethodName", BindingFlags.Static| BindingFlags.NonPublic);

var result = mInfo.Invoke(null, null) // (replace 2nd null with an array of parameters if necessary)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top