c# - 如何在调用同一类的方法时重置初始化
问题描述
下面我有一个工人阶级,有一个 foreach。
在forach里面有服务调用,可以是 GetX()、GetY() ...
作为实现,我必须根据参数重新初始化Api客户端,有没有模式可以避免_aService.SetApiClient(p)行?
public class Worker
{
private readonly IAService _aService;
public Worker(IAService entryPointService)
{
_aService = entryPointService;
}
protected void ExecuteAsync()
{
while (true)
{
new List<string>() { "x", "y", "z" }.ForEach(p =>
{
_aService.SetApiClient(p);
_aService.GetX();
// OR _aService.GetY(),_aService.GetYZ();//
});
}
}
}
public class AService : IAService
{
private GoogleApiClient _googleApiClient;
public AService(GoogleApiClient apiClient)
{
_googleApiClient = apiClient;
}
public void SetApiClient(string param)
{
_googleApiClient = new GoogleApiClient(new AuthProvider (param));
}
public string GetX()
{
return _googleApiClient.CallX();
}
}
public interface IAService
{
void SetApiClient(string param);
string GetX();
}
public interface IGoogleApiClient
{
string CallX();
string CallY();
string CallZ();
}
public class GoogleApiClient : IGoogleApiClient
{
private AuthProvider _param;
public GoogleApiClient(AuthProvider param)
{
_param = param;
}
public string CallX()
{
return DoSomeCal("X", _param);
}
public string CallY()
{
return DoSomeCal("Y", _param);
}
public string CallZ()
{
return DoSomeCal("Z", _param)
}
}
请注意,字符串列表值可以是任何东西
解决方案
您的 api 客户端确实不需要保存状态。(私有字段})它是一个服务/网关类。而是将参数传递给方法 egGetX(string param}。
推荐阅读
- flutter - 从颤振发送一个信号通知
- bash - 如何知道 SSH 密钥的长度和类型?
- ruby-on-rails - 在 rspec 测试期间,超出范围错误,Type::Integer
- angular - 我不知道是什么在路由中不断崩溃
- asp.net - 将访问令牌从一个网站传递到另一个网站
- asp.net-core - 无法让 Odata 7.1 在 web api (.net core 2.2) 中工作
- android - 如何修复Android中的android资源链接失败错误
- java - 占位符的 setImageDrawable 与 setBackground
- javascript - 无法使用 this.id 为输入字段设置 ID
- javascript - 如何模拟回调函数以进行测试,该函数位于另一个函数的参数中