访问c#中的多端点web服务(ASMX)最佳实践



我有一个提供微服务的干净架构项目,其中之一是访问Agresso ERP web服务。

https://***************/service.svc

它提供许多服务

  • https://**/service.svc?FooService/Foo
  • https://**/service.svc?BooService/Boo

每个都有自己的服务引用(连接的服务(,每个都有许多方法。

每次调用到任何一个端点都需要传递凭据。

var fooSoapClient = new FooSoapClient();
var credentials = new WSCredentials
{
Username = "fakeuser",
Password = "fakepassword",
Client = "fakeclient",
};
var result =  fooSoapClient.GetFoosAsync(Foo filter,true,
credentials ); 

(p.S(凭证类存在于所有实体中

namespace Foo1NS
{
public partial class WSCredentials : object
{
public string Username {get;set;}
public string Client {get;set;}
public string Password {get;set;}
}
}

namespace Foo2NS
{
public partial class WSCredentials : object
{
public string Username {get;set;}
public string Client {get;set;}
public string Password {get;set;}
}
}

我可以毫无问题地访问所有端点。

我有以下问题:

  • 有没有一个通用的解决方案可以让我不陷入干燥
  • 有没有一种设计模式最适合这个问题

这是我过去所做的,如果你也使用依赖注入/容器,它非常适合。这里的关键是定义一个所有服务都将实现的单一接口。使用这个的代码应该只使用接口。

每个类都应该实现您定义的接口,例如IWebServiceOperations

public interface IWebServiceOperations
{
WebServiceOperationResult GetFooAsync(WebServiceOperationRequest request);
}

我将让您计算WebServiceOperationResult/Request类,它们只包含您的请求/响应变量,包括凭据。

然后,您需要实现的每个Web服务都在一个单独的类中完成。您还可以在构造函数中指定这是什么类型的实现(FooSoap1与FooSoap2(,例如

public class FooSoapClient : BaseClient, IWebServiceOperations
{  
public FooSoapClient() : base(Clients.FooSoap1) 
public GetFooAsync(...)
{
...
}  
}
public class BaseClient
{
private readonly eFooServiceType _serviceType;
public eFooServiceType ServiceType {
get{
return _serviceType;
}
}
protected BaseClient(eFooServiceType service)
{
_serviceType = service;
}
}

现在你应该有一堆类引用了。要么你的DI容器可以根据你想要的服务类型为你解析这些,要么你可以将它们添加到字典中,所以如果你想对FooSoap1进行操作,你可以…

var fooSoapClient1 = myServices[Clients.FooSoap1];
await fooSoapClient1.GetFooAsync(...)

最新更新