Login Register






Load/Unload assembly filter_list
Author
Message
Load/Unload assembly #1
Yo.

So for anyone who's ever dove into dynamic loading, or just used Assembly.Load may have wondered, well, what if I want to unload the file now?

There're many reasons to need to do this, but you'll notice that there's no function called Assembly.Unload! So what, is it impossible?

No! You'll notice that Assembly.Load loads the specified assembly into the CURRENT AppDomain, you'll also notice that you can indeed unload an AppDomain. So what's next? Just create a fresh AppDomain and just load the assembly into it and call it a day? Well sadly you have to understand how AppDomains work, we're creating a fresh AppDomain here, meaning it will not have any of the dependencies loaded that may/are required to run your assembly. To do this we can extend the MarshalByRefObject class and do a few things.

Code:
internal class AppdomainLoad : MarshalByRefObject { private Assembly _assembly; public void LoadAssembly(byte[] data) { _assembly = Assembly.Load(data); } public object ExecuteStaticMethod(string strClass, string methodName, params object[] parameters) { var MyType = _assembly.GetType(strClass); var inst = _assembly.CreateInstance(MyType.FullName); var MyMethod = MyType.GetMethod(methodName); return MyMethod.Invoke(inst, parameters); } }

There's our AppDomain load class, and here's an example of how we use it:
Code:
AppDomain newDomain = AppDomain.CreateDomain(String.Empty, AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation); AppdomainLoad aLoader = (AppdomainLoad)newDomain.CreateInstanceAndUnwrap(typeof(AppdomainLoad).Assembly.FullName, typeof(AppdomainLoad).FullName); aLoader.LoadAssembly(loader); aLoader.ExecuteStaticMethod("ClassName", "MethodName"); AppDomain.Unload(newDomain);

As seen above we create a new AppDomain, create a new Instance, Unwrap it, and then cast it to our MarshalByRefObject extension, from there we load our assembly now that all the references are taken care of and call whatever functions we please. It's also not necessary to unload the AppDomain, however, in my case it was.


Originally from: http://www.c-sharpcorner.com/UploadFile/...eflection/
However his code is a mess, so I've cleaned it up and got it functioning properly.


Reply

RE: Load/Unload assembly #2
This thread has no love...shame.
Also doesn't this only work with other CLR assemblies?

Reply

RE: Load/Unload assembly #3
(08-30-2016, 06:30 PM)Axi Wrote: This thread has no love...shame.
Also doesn't this only work with other CLR assemblies?

Sadly yes, as much as I wish it was this easy for native files it isn't Sad


Reply

RE: Load/Unload assembly #4
(08-30-2016, 10:36 PM)Killpot Wrote:
(08-30-2016, 06:30 PM)Axi Wrote: This thread has no love...shame.
Also doesn't this only work with other CLR assemblies?

Sadly yes, as much as I wish it was this easy for native files it isn't Sad

Ah, that's a shame. Well, there's always RunPiss.

Reply