Christian
Christian

Reputation: 4375

C# Reflection, AppDomain: Execute same assembly from different folders

I have the following situation. There are n folders, each containing two assemblies:

Assembly1.dll and Assembly2.dll

In my program, I would like to create an instance of some class inside Assembly1 and call a method on that class:

for(int i = 0; i < 100; i++)
{ 
    Assembly myAssembly1 = Assembly.LoadFrom("Directory"+ i + "\\Assembly1.dll");
    Type myType = myAssembly1.GetType("MyClass");

    object myObject = Activator.CreateInstance(myType);
    myType.Invoke(myMethodName, BindingFlags.InvokeMethod, null, myObject, null);
}

This piece of code gets executed for each folder containing an Assembly1.dll The problem is that the first one works fine but afterwards the Assembly2.dll has already been loaded and will not be reloaded. However, it needs to be replaced by the one which is inside the current folder (number i). This is because it is slightly different.

At the moment each time I call the above piece of code, the same assembly2 will be taken.

I have already searched for similar questions and I found some suggestions about using custom AppDomains. I tried this, but I could not get it to work properly.

Could someone give a code example of how to initialize a new AppDomain and execute the above mentioned code inside this new domain (so that the referenced Assembly2.dll will be loaded and unloaded correctly)?

Or does anyone have a different idea of how to solve that problem?

Best wishes, Christian

Upvotes: 0

Views: 4056

Answers (2)

Christian
Christian

Reputation: 4375

I finally got it working. For all of you with the same problem, this is the solution:

AppDomain myDomain = AppDomain.CreateDomain("MyDomain");

string pathToTheDll = "C:\\SomePath\\MyAssembly1.dll";
object obj = myDomain.CreateInstanceFromAndUnwrap(pathToTheDll, "MyAssembly1.TypeName");
Type myType = obj.GetType();

myType.InvokeMember("SomeMethodName", BindingFlags.InvokeMethod, null, obj, null);

AppDomain.Unload(myDomain);

I hope this helps someone!

Upvotes: 0

Yahia
Yahia

Reputation: 70369

check this http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx and this http://msdn.microsoft.com/en-us/library/ff527268.aspx out... you can create AppDomains, load assembly1 and assign a handler for AssamblyResolve Event where you can feed it the correct Assembly2... see Can I specify dependency directories when dynamically loading assemblies?

Upvotes: 1

Related Questions