mardi 26 mai 2015

Load a DLL into a diferent AppDomain and his dependencies

I'm having a bit trouble to load a DLL by reflection in a different AppDomain.

This is my scenario.

  1. I have a DLL called Interfaces.DLL which only contains an interface Definition.
  2. Test.DLL include Interfaces.DLL and define a class called Connector, wich implements the interface defined on previous dll.
  3. I have an app wich only include Interfaces.dll and needs to load Test.dll using reflection
  4. I call a public method of class connector which returns me the DLL version of the dll file loaded by reflection. After that, I call a web service to check if i have the greater version of the file. If not, I have to unload the dll, remove the file, and download the new file.

The problem is on step 3. When i try to load Test.DLL in a diferent AppDomain, i get an error because it cannot find Interfaces.Dll in the AppDomain. The message is:

System.IO.FileNotFoundException was unhandled
 FileName=BankInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

So, how can I load 2 diferent Dll in a AppDomain?

This is my code:

Interface.DLL

Public Interface BankInterface
       Function getDLLVersion() As Double
       'Other methods here
End Interface

Test.DLL

Public Class Connector
    Implements BankInterfaces.BankInterface
    Public Function getDLLVersion() As Double Implements BankInterfaces.BankInterface.getDLLVersion
         Return 2.5
    End Function

MainApplication

Public Sub Main()
    Dim domainSetup As New AppDomainSetup
    domainSetup.ApplicationName = appDomainName
    domainSetup.ApplicationBase = "C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\"

    Dim LocalAppDomain As AppDomain = AppDomain.CreateDomain("BankDLL" & Guid.NewGuid.ToString.GetHashCode.ToString("x"), Nothing, domainSetup)
    AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf CurrentDomain_AssemblyResolve

    LocalAppDomain.CreateInstanceFrom("C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\TestDLL.dll", "TestDLL.Connector") 'This line throw the error
    Dim conector As Type = LocalAppDomain.GetType()

    'Irrelevant code here
end sub

Private Function CurrentDomain_AssemblyResolve(ByVal sender As Object, ByVal args As ResolveEventArgs) As Assembly
    Try
        Dim myassembly As Assembly = Assembly.Load(args.Name)
        If Not IsNothing(myassembly) Then
            Return myassembly
        End If
    Catch ex As Exception
    End Try

    Dim parts As String() = args.Name.Split(",")
    Dim myfile As String = "C:\Users\jferrer.GLOBAL\AppData\Roaming\Enterprise\AppName\DllFiles\" & parts(0).Trim() & ".dll"

    Return Assembly.LoadFrom(myfile)
end function





Aucun commentaire:

Enregistrer un commentaire