我正在开发一种解决方案,它将连接到各种服务器以读取数据和执行操作。 有许多变量使可靠通信复杂化,例如防火墙,停止/失败服务,身份验证差异和各种软件配置。 我可以使用一些方法来解决这些问题,但在执行时不知道哪些方法会成功。
我的目标是创建一个可用于执行操作的接口和实现。 第一个方法调用将是最快的实现,它适用于大多数设备,然后是其他可以处理前面列出的问题的调用。
在一个完美的世界中,将编写该过程以快速识别哪种方法会成功,但在我的测试中,处理时间与仅仅捕获异常一样多。 虽然性能始终是一个考虑因素,但最终成功完成任务更为重要。
下面是我创建的一个示例,它演示了迭代实现列表的最坏情况。 虽然这适用于一种方法,但在20或更多不同操作中使用时,它不遵循DRY原则。 一种可能的解决方案是Unity和Interception但我发现调用处理程序中的invoke方法使用已解析的实现,而不是可能的实现列表。 除非我遗漏了某些东西,否则这似乎不是一种选择。 此外,我将需要为几个接口遵循此模式,因此创建一个可以迭代实现列表的通用处理程序会很好。
任何有关如何完成此任务的建议将不胜感激!
接口
public interface IProcess
{
int ProcessItem(string workType);
}
实现
public class ProcessImplementation1 : IProcess
{
public int ProcessItem(string workType)
{
throw new TimeoutException("Took too long");
}
}
public class ProcessImplementation2 : IProcess
{
public int ProcessItem(string workType)
{
throw new Exception("Unexpected issue");
}
}
public class ProcessImplementation3 : IProcess
{
public int ProcessItem(string workType)
{
return 123;
}
}
特殊实现循环执行其他实现,直到成功无异常
public class ProcessImplementation : IProcess
{
public int ProcessItem(string workType)
{
List<IProcess> Implementations = new List<IProcess>();
Implementations.Add(new ProcessImplementation1());
Implementations.Add(new ProcessImplementation2());
Implementations.Add(new ProcessImplementation3());
int ProcessId = -1;
foreach (IProcess CurrentImplementation in Implementations)
{
Console.WriteLine("Attempt using {0} with workType '{1}'...",
CurrentImplementation.GetType().Name, workType);
try
{
ProcessId = CurrentImplementation.ProcessItem(workType);
break;
}
catch (Exception ex)
{
Console.WriteLine(" Failed: {0} - {1}.",
ex.GetType(), ex.Message);
}
Console.WriteLine();
if (ProcessId > -1)
{
Console.WriteLine(" Success: ProcessId {0}.", ProcessId);
}
else
{
Console.WriteLine("Failed!");
}
return ProcessId;
}
}
}