samedi 7 janvier 2017

Load a .NET assembly from the application's resources and run It from memory, but without terminating the main/host application

INTRODUCTION


I'm using the next C# code example shared by David Heffernan' for loading a .NET assembly from the application's resources and run It from memory:

Assembly a = Assembly.Load(bytes);
MethodInfo method = a.EntryPoint;
if (method != null)
    method.Invoke(a.CreateInstance(method.Name), null);

Here I just share an adaptation to use it as a ganeric usage method, in VB.NET:

Public Shared Sub Execute(ByVal resource As Byte(), ByVal parameters As Object())

    Dim ass As Assembly = Assembly.Load(resource)
    Dim method As MethodInfo = ass.EntryPoint

    If (method IsNot Nothing) Then
        Dim instance As Object = ass.CreateInstance(method.Name)
        method.Invoke(instance, parameters)
        If (instance IsNot Nothing) AndAlso (instance.GetType().GetInterfaces.Contains(GetType(IDisposable))) Then
            DirectCast(instance, IDisposable).Dispose()
        End If
        instance = Nothing
        method = Nothing
        ass = Nothing

    Else
        Throw New EntryPointNotFoundException("Entrypoint not found in the specified resource. Are you sure it is a .NET assembly?")

    End If

End Sub

PROBLEM


The problem is that if the executed assembly has an application exit instruction, then it also terminates my main/host application too. For example:

ConsoleApplication1.exe compiled from this source-code:

Module Module1
    Sub Main()
        Environment.Exit(0)
    End Sub
End Module

When I load and run ConsoleApplication1.exe with the Assembly.Load methodology, it also terminates my application because the call to Environment.Exit.

QUESTION


How can I prevent this, without modifying the source code of the executed assembly?.

PS: Please note that I want the assembly to be ran synchronuslly, not async... in case of that matters for a possible solution.





Aucun commentaire:

Enregistrer un commentaire