如何从WCF服务引用单元测试通用服务代理

时间:2013-09-06 19:19:12

标签: c# wcf generics proxy

我希望使用供应商的SOAP API并通过我们自己的统一WCF实现来公开它。由于我无法控制源服务接口,因此我被迫使用服务参考和代码生成客户端类。

其中一个客户端类的示例

public partial class CompanyApiSoapClient : System.ServiceModel.ClientBase<Cwx.Repository.ConnectWise.CompanyService.CompanyApiSoap>, Cwx.Repository.ConnectWise.CompanyService.CompanyApiSoap

为了一般地处理对不同服务的调用,我采用了以下通用代理方法:

public class ServiceClientProxy<TChannel> : IServiceClientProxy<TChannel> where TChannel : ICommunicationObject
{
    private readonly TChannel _innerChannel;
    public ServiceClientProxy(TChannel innerChannel)
    {
        _innerChannel = innerChannel;
    }

    public TResult Execute<TResult>(Func<TChannel, TResult> operation)
    {
        var result = default(TResult);

        try
        {
            if (_innerChannel.State != CommunicationState.Opened)
            {
                _innerChannel.Open();
            }
            result = operation(_innerChannel);
        }
        catch (CommunicationException)
        {
            _innerChannel.Abort();
        }
        catch (TimeoutException)
        {
            _innerChannel.Abort();
        }
        catch (Exception)
        {
            _innerChannel.Abort();
            throw;
        }
        return result;
    }

    public void Dispose()
    {
        _innerChannel.Close();
    }
}

这就是我的问题所在。为了使我的代理通用工作,TChannel需要实现ICommunicationObject。我没有从CompanyApiSoap接口获得该实现,而是具体的ClientBase通用实现。当然,如果我想通过IoC容器单元测试服务代理泛型的使用,我不能将泛型类型约束为具体类型。

0 个答案:

没有答案