How can I kill a dll loaded with reflection [duplicate] - c#

I would like to know how to unload an assembly that is loaded into the main AppDomain.
I have the following code:
var assembly = Assembly.LoadFrom( FilePathHere );
I need/want to be able to unload this assembly when I am done.
Thanks for your help.

For .net versions core 3.0 and later:
You can now unload assemblies. Note that appdomains are no longer available in .net core. Instead, you can create one or more AssemblyLoadContext, load your assemblies via that context, then unload that context. See AssemblyLoadContext, or this tutorial that simulates loading a plugin then unloading it.
For .net versions before .net core 3, including netframework 4 and lower
You can not unload an assembly from an appdomain. You can destroy appdomains, but once an assembly is loaded into an appdomain, it's there for the life of the appdomain.
See Jason Zander's explanation of Why isn't there an Assembly.Unload method?
If you are using 3.5, you can use the AddIn Framework to make it easier to manage/call into different AppDomains (which you can unload, unloading all the assemblies). If you are using versions before that, you need to create a new appdomain yourself to unload it.

I also know this is very old, but may help someone who is having this issue!
Here is one way I have found to do it!
instead of using:
var assembly = Assembly.LoadFrom( FilePathHere );
use this:
var assembly = Assembly.Load( File.ReadAllBytes(FilePathHere));
This actually loads the "Contents" of the assembly file, instead of the file itself. Which means there is NOT a file lock placed on the assembly file! So now it can be copied over, deleted or upgraded without closing your application or trying to use a separate AppDomain or Marshaling!
PROS: Very Simple to fix with a 1 Liner of code!
CONS: Cannot use AppDomain, Assembly.Location or Assembly.CodeBase.
Now you just need to destroy any instances created on the assembly.
For example:
assembly = null;

You can't unload an assembly without unloading the whole AppDomain. Here's why:
You are running that code in the app domain. That means there are potentially call sites and call stacks with addresses in them that are expecting to keep working.
Say you did manage to track all handles and references to already running code by an assembly. Assuming you didn't ngen the code, once you successfully freed up the assembly, you have only freed up the metadata and IL. The JIT'd code is still allocated in the app domain loader heap (JIT'd methods are allocated sequentially in a buffer in the order in which they are called).
The final issue relates to code which has been loaded shared, otherwise more formally know as "domain neutral" (check out /shared on the ngen tool). In this mode, the code for an assembly is generated to be executed from any app domain (nothing hard wired).
It is recommended that you design your application around the application domain boundary naturally, where unload is fully supported.

You should load your temporary assemblies in another AppDomain and when not in use then you can unload that AppDomain. It's safe and fast.

If you want to have temporary code which can be unloaded afterwards, depending on your needs the DynamicMethod class might do what you want. That doesn't give you classes, though.

Here is a GOOD example how to compile and run dll during run time and then unload all resources:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm

I know its old but might help someone. You can load the file from stream and release it. It worked for me. I found the solution HERE.
Hope it helps.

As an alternative, if the assembly was just loaded in the first place, to check information of the assembly like the publicKey, the better way would be to not load it,and rather check the information by loading just the AssemblyName at first:
AssemblyName an = AssemblyName.GetAssemblyName ("myfile.exe");
byte[] publicKey = an.GetPublicKey();
CultureInfo culture = an.CultureInfo;
Version version = an.Version;
EDIT
If you need to reflect the types in the assembly without getting the assembly in to your app domain, you can use the Assembly.ReflectionOnlyLoadFrom method.
this will allow you to look at they types in the assembly but not allow you to instantiate them, and will also not load the assembly in to the AppDomain.
Look at this example as exlanation
public void AssemblyLoadTest(string assemblyToLoad)
{
var initialAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4
Assembly.ReflectionOnlyLoad(assemblyToLoad);
var reflectionOnlyAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //4
//Shows that assembly is NOT loaded in to AppDomain with Assembly.ReflectionOnlyLoad
Assert.AreEqual(initialAppDomainAssemblyCount, reflectionOnlyAppDomainAssemblyCount); // 4 == 4
Assembly.Load(assemblyToLoad);
var loadAppDomainAssemblyCount = AppDomain.CurrentDomain.GetAssemblies().Count(); //5
//Shows that assembly is loaded in to AppDomain with Assembly.Load
Assert.AreNotEqual(initialAppDomainAssemblyCount, loadAppDomainAssemblyCount); // 4 != 5
}

Related

.Net Application Memory Management

Could be a very naive question, but was wondering how this stuff works: Lets assume that we have 10 projects in Visual Studio, and 5 of them have references to an external DLL (say Ext.dll), using a relative path.
Now when my application is deployed an running on client machine, would Ext.dll get loaded 5 times in memory? Or would it just get loaded once and gets used by other referencing projects?
Assembly will be loaded only once in memory.
CLR first check if assembly already loaded in current AppDomain, if not than assembly gets loaded under AppDomain otherwise symbols are resolved from the already loaded assembly.
Ofcourse unless you are manually creating another AppDomain which has its own set of assemblies.
Moreover, assembly with same version cannot be loaded in memory at
same time. CLR doesn't allow that. But you can have different versions
of same assembly to be loaded in memory and that too in case
assemblies are strongly signed. But in your case version is same so CLR won't load same assembly twice anyhow.
If you want to check at certain interval time that what assemblies are loaded in a memory, you can use this piece of code to get all loaded assemblies:
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
Clr load assembly in memory just once.
Note :for each instance of application Clr load assembly again.
You can read Clr via c#.In chapter one you can learn many of these Concepts.

C# Load different versions of assembly to the same project

I'm creating some tool what performs several operations like NUnit.
Inside this tool I open .dll assembly and invoke methods form it to run some test.
Everything is going OK till the time I need to reload .dll withour program restart. The idea is that when tool is run we copy required assembly to some temporary folder and invoke from there. If I need to reload I copy another one to another temporary folder and try to load newly copied from another folder and load to previous assembly object
ExecutingAssembly = Assembly.LoadFrom(AssemblyFullPath);
But my problem is that after I change AssemblyFullPath to new one and call Assembly.LoadFrom it returns just old assembly what was loaded first time but not the second one!
Maybe the problem is that we cannot load several assemblies with different versions? What is the solution?
The CLR does support loading multiple versions of strongly named assemblies into the same AppDomain. This only works though if your assemblies are strongly named and each one has a different version than the other.
I'm guessing it's more likely that you are dealing with unsigned assemblies. If that is the case then what you're asking for isn't really possible. Once a given assembly is loaded into an AppDomain it will remain there until the AppDomain is unloaded. To get this to work you will have to abstract out all of the work around the loaded assemblies into a separate AppDomain and use a new AppDomain for every assembly
To expand on JaredPar's answer, you will need to create a new AppDomain and use Remoting to communicate between the two.
Check out http://msdn.microsoft.com/en-us/library/kwdt6w2k(v=vs.85).aspx to help get you started.
Try like this:
string dllFile = "C:\\sample.dll";
Assembly asmLoader = Assembly.LoadFile(dllFile);
Type[] types = asmLoader.GetTypes();
Since all resources from the assembly cannot be reloaded/replaced it's assembly resources while application is still running. It will only be replaced/removed when application is unloaded or the that Assembly that holds it.
Use LoadFile() method. Hope it helps.

FileVersionInfo.GetVersionInfo shows wrong version for a replaced file

Why is it that when a .NET DLL is loaded, replaced from another app domain (DLL is updated with a new version), and then reloaded (using Assembly.LoadFrom) that the version info still reflects the old version?
The same is observed with assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false) or assembly.GetCustomAttributes(typeof(AssemblyVersionAttribute), false).
Is this the normal behavior? If I inspect the file in Explorer, I see the correct version, though.
Is there any way to get the actual version of the DLL?
It isn't very clear, but the term "re-loaded" is a strong indicator for what you see. The CLR will not permit reloading a different version of the same assembly with Assembly.LoadFrom(). This is a strong DLL Hell counter measure and avoids a lot of nasty runtime exceptions. In particular InvalidCastExceptions that say "Cannot cast Foo to Foo". Type identity in .NET includes the [AssemblyVersion] of an assembly. Calling Assembly.LoadFrom() will just return a reference to the previously loaded assembly.
Nor is there a way to unload an assembly from an AppDomain. Only thing you can do is create a new AppDomain.
I should not mention Assembly.LoadFile(), it doesn't perform this check, that's major misery.
When you load an assembly into an AppDomain, you cannot unload it. So replacing the file and reloading it in an AppDomain that already loaded the assembly simply does not work (that's by design). You need a new AppDomain to load the replaced assembly.

Unload AppDomain Assembly

I want to read some information from a .Net assembly, then modify the DLL by appending a short sequence of characters.
The first part works fine, but the second step fails, as the assembly is still in use.
This is the case although I loaded the assembly in its own AppDomain and after I finished step 1 unloaded the AppDomain.
Your best bet is to use something like Cecil that allows you to inspect and rewrite assemblies without loading them in the AppDomain.
References from assemblies loaded into a separate AppDomain have a nasty habit of "leaking" into the parent AppDomain, especially if you're reflecting the assembly and exchanging Type information across the boundary. There are lots of "gotchas" with keeping assemblies isolated in AppDomains truly segregated.
However, there's good news: you probably don't need to worry about the assembly being unloaded in order to modify it on disk - just use shadow copying! Create an AppDomainSetup instance, set its ShadowCopyFiles property to true, and pass it when you create the new AppDomain. This will cause the assembly to be copied to a temporary file before being loaded, keeping the original assembly unlocked and available for modification.
You cannot unload an assembly without unloading the AppDomain:
http://msdn.microsoft.com/en-us/library/ms173101(VS.80).aspx
There is no way to unload an
individual assembly without unloading
all of the application domains that
contain it. Even if the assembly goes
out of scope, the actual assembly file
will remain loaded until all
application domains that contain it
are unloaded.
Are you sure that no other process or AppDomain is using the assembly?

Why are some .Net assemblies not available via an AppDomain's GetAssemblies() method?

I have a little bit of code that loops through the types currently loaded into an AppDomain that runs in an ASP.NET application. Here's how I get the assemblies:
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
When the application first starts up there is no problem and all the types I expect are present. But when I update the Web.config or kill the w3p.exe process (or the process gets recycled for whatever reason) only some of the types I'm expecting are available. When I step through with a debugger I notice that certain assemblies from the private search path (the bin directory of my application) haven't been loaded. I was under the assumption that all assemblies were loaded at application start and restart whether or not they were immediately required. But in the case of restarting this doesn't seem to be happening unless those assembly files have been updated.
What I require is to collect type information at start-up for use later. But since during a restart the types aren't available it reeks havoc later on when the type information needs to be used. So with that in mind how can I solve or work around this deficiency?
Assemblies are loaded on demand, so it could be that you did not used any type contained in these assemblies yet.
You can use
AssemblyName[] assemblies = Assembly.GetCallingAssembly().GetReferencedAssemblies();
This way, you get all assemblies that are referenced from the assembly from which you are calling these method.
As a part of startup, can you explicitly load the assemblies you care about?
You would have to know ahead of time which assemblies you would need.
Scanning the filesystem to find out which assemblies have been shipped along with your app may be a useful idea, but it won't help for GAC loaded assemblies...

Categories

Resources