0

I have base and derived classes:

public abstract class DataServiceBase {
  public abstract List<Data> GetData(String name);
}

public class DataService : DataServiceBase {
  public override List<Data> GetData(String name) {

     // GetData from API
     // Call Interceptor.Register(List<Data> data)
     return data;
  }
}

I would like the derived classes to call Interceptor.Register(List<Data> data) in GetData before returning the data.

Is there a way to make sure that this always happens?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

Yes, the template method pattern, as Alexander suggested. Here, we implement GetData in the abstract base class, which calls the GetDataInternal (for a lack of a better name) hook. The hook is implemented in each derived class and is called when you call GetData (which also calls your interception code).

public abstract class DataServiceBase
{
    public List<Data> GetData(String name)
    {
        var data = GetDataInternal(name);
        Interceptor.Register(data);
        return data;
    }

    internal abstract List<Data> GetDataInternal(String name);
}

public class DataService : DataServiceBase
{
    internal override List<Data> GetDataInternal(String name)
    {
        var data = new List<Data>();
        // GetData from API
        return data;
    }
}
Gerardo Grignoli
  • 14,058
  • 7
  • 57
  • 68