lundi 1 avril 2019

How to create a Fluent Interface that works in specific order [duplicate]

This question already has an answer here:

Hello i am trying to create a fluent API for an object.I create a builder object that will get its dependencies and then i will build the resulting object. The problem is that i need to perform some async operations using those dependencies to be able to spawn the final object.

public class MyObject
{
   private object finalDependency;
   MyObject(object dependency)
  { 
     this.finalDependency=dependency;
  }
}
public class MyBuilder
{
  public int Dep1 {get;set;}
  public int Dep2 {get;set;}


}
public static class MyBuilderExtension
{
   public static MyBuilder SetDependency1(this MyBuilder obj,int dep1)
   {
       obj.Dep1=dep1;
       return obj;
   }
   public static MyBuilder SetDependency1(this MyBuilder obj,int dep2)
   {
       obj.Dep1=dep2;
       return obj;
   }
   public static MyObject BuildAsync(this MyBuilder obj)
   { 
      var d1=await OperationAsync1(obj.Dep1);
      var d2=await OperationAsync2(obj.Dep2);
      var dep=await OperationAsync(d1,d2);
      return new MyObject(dep);
   }
}

As you can see i am performing all required async operations in the final method since i cannot otherwise guarantee that the actions are performed in a specific order ( dep1->dep2 )

What would an alternative be if i don't want to mash them up in the final operation BuildAsync.
I know i could make set them one by one using async all the way...but in my case i need to respect an order.Ican't perform an async operation before another.Keeping them at the end gives me control and only me to construct the object.

What would be other alternatives to reach something like:

-create builder
-set field1  (async)
-set field2  (async)
-build 

where the user is forced to first set field 1 and then 2?

P.S Even though in the aforementioned example the operations seem not related to each other, and thus you might say what i need is useless since they aren't dependent, they are.And i have to do them in a specific order !

Aucun commentaire:

Enregistrer un commentaire