简体   繁体   English

在多个Web服务引用中动态使用相同的方法?

[英]Dynamically using same method in multiple web service references?

In c# .Net Framework 4.5 (Visual Studio Ultimate 2012, Version 11.0.61219.00 Update 5), I'm trying to define a service variable at runtime for which webservice to use. 在c#.Net Framework 4.5(Visual Studio Ultimate 2012,版本11.0.61219.00更新5)中,我试图在运行时定义要使用的Web服务的服务变量。 Each webservice (there are many) are all defined the same except for the endpoint url but the credentials will not cross over to authenticate. 每个Web服务(有很多)都被定义为相同的(端点URL除外),但是凭据不会越过以进行身份​​验证。 The below condition is menial to simplify the issue at hand. 以下条件很容易简化当前问题。 The following code gives the error: Cannot implicitly convert type WebService2.Service to WebService1.Service . 下面的代码给出了错误:无法将类型WebService2.Service隐式转换为WebService1.Service

What I've tried: calling functions to return the proper service but the parameters or assignment all require a specific type. 我已经尝试过:调用函数以返回正确的服务,但是参数或赋值都需要特定的类型。

var service = new WebService1.Service();
service = new WebService2.Service();

I want to be able to use the variable service in the rest of the program without having to duplicate code everywhere for using the many web service references. 我希望能够在程序的其余部分中使用变量service ,而不必到处重复使用许多Web服务引用的代码。

It seems like what you are looking to do, you would need a common interface between the two services so you could inject whichever service you wish to use. 看来您要做什么,这两个服务之间将需要一个公共接口,以便您可以注入要使用的任何服务。

public class WebService1 : IWebService {...service code} 
public class WebService2 : IWebService{...service code}
public interface IWebService{...service methods you will be calling}

Then you could do the following. 然后,您可以执行以下操作。

IWebService service = new WebService1.Service();
service = new WebService2.Service();

Assuming that the different services share the same method names, you can create an interface that all of the services implement by using the interface 假设不同的服务共享相同的方法名称,则可以使用该接口创建一个由所有服务实现的接口

IMyService.cs IMyService.cs

interface IMyService
{
     void MyMethod(string filter);
}

MyWebServiceImplementation.cs MyWebServiceImplementation.cs

public class MyWebServiceImplementation : IMyService
{
    public void MyMethod(string filter);
}

MySecondWebServiceImplementation.cs MySecondWebServiceImplementation.cs

public class MySecondWebServiceImplementation : IMyService
{
    public void MyMethod(string filter);
}

MyImplemetationCode.cs MyImplemetationCode.cs

//Use different services from same variable

IMyService service = new MyWebServiceImplementation();
service.MyMethod("filter");
service = new MySecondWebServiceImplementation();
service.MyMethod("another filter");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM