如何在带有配置文件的 Powershell 脚本中使用自定义 WCF 代理?

2024-03-21

我在它自己的程序集中有一个手写的 WCF 代理,它非常简单:

public class MyServiceClient : ClientBase<IMyService>, IMyService
{
    public MyServiceClient()
    {
    }

    public MyServiceClient(string endpointConfigurationName) :
        base(endpointConfigurationName)
    {
    }
}

我将其加载到 Powershell 脚本中:

Add-Type -Path "$LocalPath\MyService.Client.dll"
Add-Type -Path "$LocalPath\MyService.Contracts.dll"

然后我尝试设置 App.config (按照其他帖子 https://stackoverflow.com/questions/835862/powershell-calling-net-assembly-that-uses-app-configon SO),以便可以使用配置中定义的端点实例化客户端,而不是在脚本本身中:

[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "$LocalPath\MyService.Client.dll.config")

我已经检查了 AppDomain 并将配置文件设置为其ConfigurationFile财产。

当我创建客户端实例时:

$endpointName = "MyServiceHttpEndpoint" # defined in the app.config file
$myclient = New-Object MyService.Client.MyServiceClient($endpointName)

它倒下说:

Exception calling ".ctor" with "1" argument(s): "Could not find endpoint element with name 'MyServiceHttpEndpoint' and contract 'MyService.Contracts.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element."

有任何想法吗?我不想在脚本文件中手动创建端点 - 它需要从配置中读取。


Powershell 和 Powershell ISE 处理此问题的方式似乎有所不同。

使用 ISE(至少是我正在使用的版本),您必须清除配置才能强制其重新加载。不过,我想您也可以将 .dll.config 文件的内容放入 powershell ISE 配置中。然而,这看起来很糟糕。下面发布的代码有效。我发现其中的一部分是通过谷歌搜索这个问题的。

# $dllPath is the path to the dll we want to load
# first point to the correct config file
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "$dllPath.config")

# PowerShell ISE is a PITA we have to override the config
if ($psISE -ne $null) {
    Add-Type -AssemblyName System.Configuration
    [Configuration.ConfigurationManager].GetField("s_initState", "NonPublic, Static").SetValue($null,0)
    [Configuration.ConfigurationManager].GetField("s_configSystem", "NonPublic, Static").SetValue($null,$null)
    ([Configuration.ConfigurationManager].Assembly.GetTypes() | where {$_.FullName -eq "System.Configuration.ClientConfigPaths"})[0].GetField("s_current", "NonPublic, Static").SetValue($null, $null)
}

#Now load the DLL
$null = [Reflection.Assembly]::LoadFrom($dllPath)

# DLL and Config should be loaded - test
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在带有配置文件的 Powershell 脚本中使用自定义 WCF 代理? 的相关文章

随机推荐