如何正确调用WCF ServiceClient代理扩展?

时间:2017-07-23 17:15:51

标签: c# wcf

在解决wcf客户端问题时,我遇到了@marc-gravell here的一些代码。我多次阅读这篇文章,然后决定尝试看看我是否可以使用真正的代码,所以我创建了一个控制台应用程序并将其全部拉进去。

打包机:

public interface IDisposableWrapper<T> : IDisposable
{
    T BaseObject { get; }
}

public class DisposableWrapper<T> : IDisposableWrapper<T> where T : class, IDisposable
{
    public T BaseObject { get; private set; }
    public DisposableWrapper(T baseObject) { BaseObject = baseObject; }
    protected virtual void OnDispose()
    {
        BaseObject.Dispose();
    }
    public void Dispose()
    {
        if (BaseObject != null)
        {
            try
            {
                OnDispose();
            }
            catch
            {
                // swallow...
            }
        }
        BaseObject = null;
    }
}

扩展:

public static class DisposableExtensions
{
    // core "just dispose it without barfing"
    public static IDisposableWrapper<T> Wrap<T>(this T baseObject)
        where T : class, IDisposable
    {
        if (baseObject is IDisposableWrapper<T>) return (IDisposableWrapper<T>)baseObject;
        return new DisposableWrapper<T>(baseObject);
    }

    // specific handling for service-model
    public static IDisposableWrapper<TProxy> Wrap<TProxy, TChannel>(this TProxy proxy)
        where TProxy : ClientBase<TChannel>
        where TChannel : class
    {
        return new ClientWrapper<TProxy, TChannel>(proxy);
    }
}

ClientWrapper:

public class ClientWrapper<TProxy, TChannel> : DisposableWrapper<TProxy>
    where TProxy : ClientBase<TChannel>
    where TChannel : class
{
    public ClientWrapper(TProxy proxy) : base(proxy)
    {
    }

    protected override void OnDispose()
    {
        // lots of code per state of BaseObject
        //State != CommunicationState.Faulted;
    }
}

现在,当我去使用它时,我有这个:

static void Main(string[] args)
{

    using (var proxy = new PLPlacementServiceClient())
    {
        var result = proxy.GetDocumentClassForNewBusiness();
    }

    using (var proxy = new PLPlacementServiceClient().Wrap())
    {
        var result = proxy.BaseObject.GetDocumentClassForNewBusiness();
    }

    using (var proxy = new PLPlacementServiceClient().Wrap<>())//what goes here?
    {
        var result = proxy.BaseObject.GetDocumentClassForNewBusiness();
    }

}

当我F-12 PLPlacementServiceClient()。Wrap()方法时,它将我带到扩展类中的非泛型实现

IDisposableWrapper<T> Wrap<T>(this T baseObject)

,但我期待被带到另一个签名

IDisposableWrapper<TProxy> Wrap<TProxy, TChannel>(this TProxy proxy)

所以这是我的问题,“如何调用扩展的ClientBase版本?”

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分:1)

您必须为方法Wrap指定两个类型参数。那就是:

using (var proxy = new PLPlacementServiceClient().Wrap<PLPlacementServiceClient,/*type of the service contract PLPlacementServiceClient is implementing*/>())
{
    var result = proxy.BaseObject.GetDocumentClassForNewBusiness();
}