如何为WCF服务执行未知方法

时间:2019-07-12 20:52:37

标签: c# wcf

我正在做一个小型宠物项目,该项目旨在编写一个应用程序以探测我们环境中的特定服务并检查健康状况。

目前,我仅关注WCF。我们想探究几种不同的服务,并且我试图尽可能地与代码无关地构建代码,以便稍后再插入单独的服务。

下面是我正在编写的接口,稍后将由各个服务实现。我现在的挣扎是我找不到一种方法来传递要执行的特定方法名称。甚至有办法做到这一点吗?

public class IWCFComponent : IDisposable
{
    private System.ServiceModel.IServiceChannel wcfService;

    public void Dispose()
    {
        Dispose();
    }

    public void LoadComponent(IServiceChannel wcfService)
    {
        _wcfService = wcfService;
    }

    public ProbeResults Test(string methodName, string expectedResult)
    {
        /*Need to know how to execute methodName for wcfService */
    }
}

1 个答案:

答案 0 :(得分:0)

最后弄清楚了。这不是完美的选择,因为我正在努力使用不同的肥皂袋,但是如果有人遇到相同的情况,这是一个好的开始:

foreach (WCFService service in _servicesToProbe)
        {
            ProbeResults probeResult = new ProbeResults();
            var watch = Stopwatch.StartNew();
            IChannelFactory<IRequestChannel> factory = service.ServiceBinding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
            factory.Open();
            EndpointAddress address = service.EndpointURL;
            IRequestChannel irc = factory.CreateChannel(address);
            try
            {
                using (irc as IDisposable)
                {
                    irc.Open();
                    StringReader sr = new StringReader(String.Format(@"<{0} xmlns='http://tempuri.org/'><composite xmlns:a='http://schemas.xmlsoap.org/soap/envelope/' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><a:value>10</a:value></composite></{0}>", service.ActionName));
                    XmlReader reader = XmlReader.Create(sr);
                    Message m = Message.CreateMessage(MessageVersion.Soap11, String.Format("http://tempuri.org/{0}/{1}", service.InterfaceName, service.ActionName), reader);
                    Message ret = irc.Request(m);
                    reader.Close();
                    factory.Close();
                    probeResult = ProcessResponse(ret, service);
                    _probeResults.Add(probeResult);
                }
            }
            catch (Exception ex)
            {
                factory.Close();
                probeResult = new ProbeResults(service.ServiceName, false, ex.Message);
                _probeResults.Add(probeResult);
            }
            watch.Stop();
            probeResult.TimeElapsed = watch.ElapsedMilliseconds;
        }