clamp
clamp

Reputation: 34026

get assembly of method

Imagine the following situation:

Assembly A is starting the program. (it has a main method)

it loads Assembly B via reflection and instantiates a class of Assembly B.

in this instance a method is called where i would like to get to the Assembly B.

i have already tried

System.Reflection.Assembly.GetCallingAssembly();

System.Reflection.Assembly.GetExecutingAssembly();

but they always give me Assembly A instead of B.

Upvotes: 2

Views: 699

Answers (3)

Adil
Adil

Reputation: 148130

Try getting type of class contain the method you are going for and get its assembly.

string assemblyName = this.GetType().Assembly.FullName;

Upvotes: 5

Hans Passant
Hans Passant

Reputation: 941585

The Assembly.GetExecutingAssembly() is the proper method to use.

You leave preciously few breadcrumbs to diagnose the cause of having trouble with it. There are however strings attached to this. An important job performed by the jitter is to make methods disappear. This is an optimization called "inlining". In effect, the call to the method is replaced by the code of the method. It is a very important optimization, it for example makes properties as cheap as using public fields. But a consequence it that you'll get the assembly of the calling method. In your case Main(). So you'll see assembly A and not B.

This is not something you ought to tinker with, avoid having a need for this. A method shouldn't be puzzled about what assembly it lives in, you could for example use the typeof(T).Assembly property where T is the class in which the method lives.

You can disable the inlining optimization, you do so with an attribute:

using System.Runtime.CompilerServices;
...

    [MethodImpl(MethodImplOptions.NoInlining)]
    public void Foo() { }

Upvotes: 4

Akshay Joy
Akshay Joy

Reputation: 1765

try this sample ,

public static object ExecuteAssemblyMethod(string methodName,Type assemblyObj, object[] arguments)
        {
            object result = null;
            try
            {
                object ibaseObject = Activator.CreateInstance(assemblyObj);
                result = assemblyObj.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, ibaseObject, arguments);

            }
            catch (ReflectionTypeLoadException emx)
            {
                result = null;
                return result;

            }
            catch (Exception ex)
            {
                result = null;
                return result;
            }
            return result;

        }

Usage:-

Assembly assemb = Assembly.LoadFile(@"D:\TEMP\TestClassLibrary_new.dll");

        Type testType = assemb.GetType("TestClassLibrary.Class1");
        object[] param = new object[] {"akshay" };
        object result = LoadAssembly.ExecuteAssemblyMethod("GetName", testType, param);

Upvotes: 0

Related Questions