mercredi 26 août 2015

Methods in reflected DLLs unable to be called. How can I get a better error message?

I'm trying to write a PowerShell script that will call a series of static methods in a static class (MyClass) contained within certain DLL (MyNamespace.MyLibrary.dll) through reflection. However, even calling the simplest of methods (MyNamespace.MyLibrary.MyClass.CallMe()) inside that library fails with the following error message:

Exception calling "CallMe" with "0" argument(s): "The type initializer for 'MyNamespace.MyLibrary.MyClass' threw an exception."
At C:\temp\powershellTest.ps1:41 char:1
+ $output = [MyNamespace.MyLibrary.MyClass...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TypeInitializationException

The first odd thing is that I'm getting a type initialization (constructor?) error when trying to call a static method in a static class.

The PowerShell code making the call:

[reflection.assembly]::LoadFile($dllLocation + 'MyNamespace.MyLibrary.dll')
$output = [MyNamespace.MyLibrary.MyClass]::CallMe()
Write-Host $output

The relevant C# code:

namespace MyNamespace.MyLibrary
{
    public static class MyClass
    {
        public static string CallMe() // the CallMe() method was added just to try to debug this
        {
            return "I was called";
        }
    }
}

Now, this particular library is much larger and has many dependencies, all used within other methods in MyClass. I made another DLL that is literally as simple as can be (no external dependencies) to test my powershell reflection, and it succeeds in calling a static class' method (also static, obviously). This tells me that my powershell is correct, so I looked up why I might be getting this issue. This comment says that it may not be automatically loading all of MyNamespace.MyLibrary's references.

I tried two things to remedy that:

  1. I copied all non-GACed DLLs referenced by MyLibrary into the same folder so they'd be side-by-side with MyLibrary.dll

  2. When that didn't work, I also added explicit [reflection.assembly]::LoadFile(path\otherAssembly.dll) lines after the one for MyNamespace.MyLibrary.dll to make sure powershell could load them. This also didn't work.

Here's my main question: How can I get a more specific error message about which dependency isn't being found and possibly where it's looking? I was shocked when Attempted Fix #1 wasn't enough, and I'm not sure what else I can do.

I hope that made sense; feel free to ask any necessary clarifying questions. Thanks!





Aucun commentaire:

Enregistrer un commentaire