Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load dll in .net without locking it

Tags:

c#

.net

dll

I Am working on a task in which i have to load dll and get some information from it like class names and etc... but when i load that dll into my code, it gets locked and can't be build from source code until i close loading program, I have tried certain solution but none of them works for me

  1. Shadowcopy: in this case when i shadow copy assembly then after that if i have changed something in
    my main dll it will be still old one in my loading application.

  2. System.Reflection.assembly.loadfrom(System.IO.GetBytes("asm-path")); //work sometimes but not always

  3. System.Reflection.assembly.ReflectionOnlyConext(); //Does not work

Is there any proper solution to this

like image 742
Numan Hanif Avatar asked Sep 21 '13 17:09

Numan Hanif


1 Answers

One way would be to read the bytes of a file and use the overload of Assembly.Load that takes in a byte array similar to what you're doing in your second example. I'm not sure what System.IO.GetBytes is but try File.ReadAllBytes instead.

byte[] assemblyBytes = File.ReadAllBytes("asm-path");
var assembly = Assembly.Load(assemblyBytes);

However this may not be enough depending on what you want to do since you can't unload an assembly after it's been loaded. To workaround this, if you need to, you could load the assembly into its own AppDomain and then unload the AppDomain once you've finished with it.

AppDomain ad = AppDomain.CreateDomain("New_Assembly_AD");
byte[] assemblyBytes = File.ReadAllBytes("asm-path");
var assembly = ad.Load(assemblyBytes);  

Once you've finished with the assembly object, you can unload the AppDomain.

AppDomain.Unload(ad);
like image 158
keyboardP Avatar answered Sep 21 '22 17:09

keyboardP