Question

I have a large number of classes inheriting from a large number of interfaces. The interfaces that these classes are implementing do not share any common methods, but they all share a common first step. An illustration of this is:

Class A looks like this:

class A : InterfaceA
{

    GetFoo(Database db)
    {
       PerformSetup(db); // This is the common first step.

       // Do foo things
    }
}

Class B might look something like this:

class B : InterfaceB
{
    GetBar(Database db)
    {
        PerformSetup(db); // This is the common first step.

        // Do bar things
    }
}

Now obviously I could just create a base class with a method PerformSetup and have all of these methods call that. But my issue is that there are very many methods, and that call to PerformSetup() needs to be in all of them, but it is not yet in any of them.

So I could certainly just copy-paste that setup code to the beginning of every single method, but in the interest of DRY and my own time, I was wondering if there was some way I could ensure this method would be automatically called before any (public-only if possible) method call? Could I make use of events somehow? Keep in mind again that no class shares a common interface, and that many of these interface methods have parameters in addition to the Database parameter, but they all do have the database parameter.

This probably a bit fantastical but I am always curious to see what crazy contraptions people are able to rig up in C#.

Was it helpful?

Solution

Two possible answers:

  1. Use PostSharp. It costs, but I guess it works.
  2. You could use reflection to call the PerformSetup method before you call your methods

Basically you can make a base class with the following

class Base
{
    public void InvokeMethodWithSetup(string method, Database db, params object[] args)
    {
        PerformSetup(db);
        var method = this.GetType().GetMethod(method);
        method.Invoke(this, args);   
    }

    public void PerformSetup(Database db)
    {
        // stuff
    }
}

This unfortunately means going to everywhere one of your methods is called to replace the invocation code, so I don't know if that makes it much easier, but at least it saves you having to modify all the methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top