views:

111

answers:

4

I'm currently writing a library in C# and was using PowerShell to quickly test it on some occasions. However, this prevents me from re-building the project as PowerShell obviously still has the DLL open.

Is there a way of unloading the DLL again after adding it with Add-Type? The documentation doesn't seem to have clues on that and the obvious candidate would be Remove-Type (which doesn't exist – there is only one command anyway with Type as its noun). It gets cumbersome to close PowerShell and do all the stuff of navigating to the build directory and adding the type again each time I want to rebuild.

A: 

I have been facing to similar problem. It is not possible to unload a type/assembly (that's because it applies to .NET framework).

In .NET you can solve it if you crate a new application domain (System.AppDomain) and load the assembly into that domain. It is possible to unload the app domain and that unloads all the dlls as well.

I haven't tried it yet, because for me it is much simpler to close a tab in Console and open new one.

stej
+1  A: 

If your assembly doesn't require a binding context you can do this:

$bytes = [System.IO.File]::ReadAllBytes("Path_To_Your_Dll.dll")
[System.Reflection.Assembly]::Load($bytes)
George Howarth
+3  A: 

Like the others say, this is a .NET behavior. Assemblies loaded into an AppDomain cannot be unloaded. Only the AppDomain can be unloaded, and powershell uses a single appdomain. I blogged a bit about this some years ago: http://www.nivot.org/2007/12/07/WhyAppDomainsAreNotAMagicBullet.aspx

When I test like this, I usually keep a shell open and use a nested shell to do tests. start powershell, cd to bin location then run "powershell" to start nested shell (new process.) "exit" to start over, and run "powershell" again.

x0n
+1  A: 

I find the simplest way to get around this problem is to wrap the Add-Type and the test cost inside of a Start-Job. Start-Job will create a background process, and the type will be loaded there. Once you are done, the process goes away and you're free to retry.

Hope this helps,

Start-Automating