在ChannelFactory Cache

时间:2018-01-19 08:34:58

标签: c# .net-core channelfactory

我已将旧库转换为.NET Core并实现了ChannelFactory缓存解决方案。它连接的服务需要向每个请求的HTTP头添加基本授权。使用ClientMesageInspector将标头添加到每个请求中。因为ClientMessageInspector在创建第一个通道后是不可变的,所以ChannelFactory缓存将每个实例存储在一个字典中,其中包含一个基于ChannelFactory端点,用户名和密码组合的键。此外,由于创建ChannelFactory的开销,我不会丢弃它们。我担心的是用户名和密码保存在字典键内的内存中,也存放在添加到ChannelFactory的ClientMesageInspector中。有更好的解决方案吗?我已经在dotnet / wcf GitHub page上提出了这个问题,并希望向更多的观众开放。

提前致谢。

鲍勃。

1 个答案:

答案 0 :(得分:0)

我通过我的question获得了dotnet / wcf团队的大力帮助。 经过一番讨论后,我最终使用AsyncLocal变量来存储用户名和密码。

在包装器类中,我们有两个AsyncLocal变量,它们是通过构造函数设置的。

internal static AsyncLocal<string> Username = new AsyncLocal<string>();
internal static AsyncLocal<string> Password = new AsyncLocal<string>();

public WCFWrapper(string username, string password) : this()
{
    Username.Value = username;
    Password.Value = password;
}

在IClientMessageInspector BeforeSendRequest方法中,我们只使用变量。

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] =  
        "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(WCFWrapper.Username.Value + ":" + WCFWrapper.Password.Value));
    request.Properties[HttpRequestMessageProperty.Name] = httpRequestProperty;

    return null;
}
相关问题