【问题标题】:C# Fluent API - How to insure dependant data is chained correctlyC# Fluent API - 如何确保正确链接相关数据
【发布时间】:2016-01-25 12:21:53
【问题描述】:

我目前正在编写一个 Fluent API(对这种模式来说非常新)。我不确定在最终执行之前确保通过先前的方法链接设置依赖数据的最佳做法是什么。

鉴于以下 API。

public class Processor : IFluentProcessor
{
   private string _connectionName = String.Empty;
   private string _whereClause = String.Empty;

   public IFluentProcessor ConnectionName(string connectionName)
   {
       _connectionName = connectionName;
       return this;
   }

   public IFluentProcessor FilterClause(string whereClause)
   {
       _whereClause = whereClause;
       return this;
   }

   public bool Execute(out string errorMessage)
   {
       errorMessage = String.Empty;

       try
       {
           //Ideally i would like to make sure that these variables have been set prior to this execution
           var client = new dbContext(_connectionName);
           var items = client.Where(_whereClause).Select(m => m).ToList();

           foreach (var item in items)
           {
               //process the items here.
           }

           return true;
       }
       catch (Exception ex)
       {
           errorMessage = ex.Message;
           return false;
       }
    }
 }

 public interface IFluentProcessor
 {
     IFluentWorker ConnectionName(string connectionName);
     IFluentProcessor FilterClause(string whereClause);
     bool Execute(out string errorMessage);
 }

有没有办法确保“配置”方法在调用执行方法之前已经被链接。而不仅仅是验证 Execute 方法中的项目。

【问题讨论】:

标签: c# .net fluent


【解决方案1】:

为了严格的排序,你可以拆分接口(请原谅我命名时缺乏灵感,你明白了):

public interface IFluentProcessor1
{
    IFluentProcessor2 ConnectionName(string connectionName);
}
public interface IFluentProcessor2
{
    IFluentProcessor3 FilterClause(string whereClause);
}
public interface IFluentProcessor3
{
    bool Execute(out string errorMessage);
}

结合私有构造函数+工厂方法来实例化流式接口:

public class Processor : IFluentProcessor1, IFluentProcessor2, IFluentProcessor3
{
    private string _connectionName = String.Empty;
    private string _whereClause = String.Empty;

    private Processor() {}
    public static IFluentProcessor1 Create() { return new Processor(); }
    // ...
}

这确实修复了调用方法的顺序,它不允许将调用切换到FilterClauseConnectionName

string errorMessage;
var result = Processor.Create()
   .ConnectionName("my connection")
   .FilterClause("my filter")
   .Execute(out errorMessage);

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多