.NET dll hot swap, no application restart

2020-08-10 08:27发布

问题:

Suppose that you have the following situation in .NET (C#):

namespace MyDll
{
    public class MyClass
    {
        public string GetValue()
        {
            return "wrong value";
        }
    }
}

this code goes compiled into a dll say, MyDll.Dll.

Then you have an application called MyApplication.exe that, using MyDll.dll as reference, creates an instance of the class MyClass and calls the method GetValue:

MyClass instance = new MyClass();
instance.GetValue();

Once you realize that the current implementation of MyClass.GetValue() is wrong is there any way to fix the method MyClass.GetValue() like this

namespace MyDll
{
    public class MyClass
    {
        public string GetValue()
        {
            return "correct value";
        }
    }
}

and HOT swapping the resulting MyDll.dll, without restarting MyApplication.exe???

All solutions proposed in stackoverflow and in google fail to work because, even if MyDll.dll is loaded on a new AppDomain created for that purpose, when I unload calling

AppDomain.Unload(anoterAppDomainJustForMyDll);

it returns without error, but if I try to overwrite the original MyDll.dll with the corrected one (while MyApplication.exe is still running) I get an error "impossible to overwrite because the dll in use by another process"....

回答1:

Question is closed by myself: please refer to article in codeplex

To me it was important to be able to hot swap the new dll without rebooting the application, and as the article proposes, this can be done, as this is done from withing the application itself. The reason why my previous attemps were failing was that I tried to overwrite the target dll from outside (in explorer in this case). But if the overwriting is done like in the proposed solution, from the application itself, it works as expected.

I will need a little bit more on application side to define directories where versionable ddls can be deployed, but this is perfectly acceptable to me.