Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load assembly into child AppDomain and releasing dll file

I have child app-domain where I want to load some dll libraries on start-up and release files so that anybody will be able to delete them.

On start-up I do

Loader al = (Loader)domain.CreateInstanceAndUnwrap(
typeof(Loader).Assembly.FullName,
typeof(Loader).FullName);
al.Load(path)

for the following class.

class Loader : MarshalByRefObject
{
    internal void Load(string path)
    {
        Assembly assembly;
        try
        {
            assembly = Assembly.Load(File.ReadAllBytes(path));
        }
        catch (Exception) { return; }
    }
    internal UseType(string fullyQualifiedTypeName)
    {
         Type userType = Type.GetType(fullyQualifiedTypeName);
    }
}

Later I invoke UseType and I get the correct type but I am not able to delete the file any more because it is as if the child app-domain has locked the dll.

Basically what I want to achieve is to cache the assembly file on start-up and later use GetType calls so that the actual dll file will be released.

Is it really possible to achieve something like this ?

like image 845
Egor Avatar asked Aug 08 '11 16:08

Egor


People also ask

How do you unload assembly from AppDomain?

To unload an assembly in the . NET Framework, you must unload all of the application domains that contain it. To unload an application domain, use the AppDomain. Unload method.

Can not load file or assembly?

In summary if you get the "Could not load file or assembly error", this means that either your projects or their references were built with a reference to a specific version of an assembly which is missing from your bin directory or GAC.

What is AppDomain in C#?

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

How do I create an app for my domain?

You can also create application domains from which you execute code. You create a new application domain using one of the overloaded CreateDomain methods in the System. AppDomain class. You can give the application domain a name and reference it by that name.


1 Answers

Use shadow copy when you create the App Domain. That copies the dlls into a cache and anyone can interact with the file system.

Topshelf does this with our shelving (everything lives in it's own app domain then) - https://github.com/Topshelf/Topshelf/blob/v2.3/src/Topshelf/Model/ShelfReference.cs#L126.

Update: Topshelf no longer does this, but updated a link to a version which did.

like image 124
Travis Avatar answered Sep 27 '22 19:09

Travis