CAKE:不安全地加载程序集

时间:2017-09-28 08:24:50

标签: c# .net powershell cakebuild

我使用CAKE 0.21.1.0。

我想添加一个执行此PowerShell操作等效的任务:

$dlls = @(${dll1}, ${dll2})
$dlls | % { [Reflection.Assembly]::UnsafeLoadFrom($_) }
[StaticClassFromLocalLibrary]::SomeStaticMethod(SomeArgument)

我决定不使用the CAKE PowerShell add-in,因为直接运行PowerShell脚本会引发错误<script>.ps1 is not digitally signed. The script will not execute on the system。由于我的雇主的IT政策,我不允许Set-ExecutionPolicy来解决问题。这就是为什么我想将PowerShell脚本中采取的步骤直接转换为CAKE中的指令。

最初,我在我的CAKE脚本中写了这些行:

System.Reflection.Assembly.UnsafeLoadFrom(dll1);
System.Reflection.Assembly.UnsafeLoadFrom(dll2);
StaticClassFromLocalLibrary.SomeStaticMethod(SomeArgument);  

然而,抛出异常,说在当前上下文中找不到名称StaticClassFromLocalLibrary

然后我将此行添加到我的CAKE脚本中:

#r @"\\hostName\Folder1\Folder2\Folder3\Folder4\Some.Local.Project.dll"

但是,因为它没有以不安全的方式加载,所以抛出了另一个异常,这次告诉我无法加载DLL。

如何使用#r指令(或任何其他CAKE命令)指定我希望以不安全的方式加载DLL?

修改

我已经通过咨询this page并在接受的答案中采纳了这个建议来解决我的问题。

1 个答案:

答案 0 :(得分:2)

Cake中没有构建不安全的加载,但因为它只是C#所能做的就是将PowerShell代码段转换为C#

var assembly = System.Reflection.Assembly.UnsafeLoadFrom("./tools/Addins/Newtonsoft.Json/lib/net45/Newtonsoft.Json.dll");

var type = assembly.GetType("Newtonsoft.Json.JsonConvert");

var method = type.GetMethod("SerializeObject", new [] {typeof(object) });

var SerializeObject = (Func<object, string>) Delegate.CreateDelegate(
                                           typeof(Func<object, string>), null, method);

var json = SerializeObject(new { Hello = "World"});

Information("{0}", json);

将输出类似

的内容
{"Hello":"World"}