DEV Community

Thomas Sarmis
Thomas Sarmis

Posted on • Updated on

AutoInvoke (Runtime method resolving and invoking)

During my years of programming I often run into the issue of dynamically (during runtime) deciding which function to call.

This may happen while developing a CLI tool where you need to call a different method based on some command line parameter or when building a command processing/routing module for some backend system.

Typically I would just solve this issue per case, but I decided to build a library for that.

I present to you AutoInvoke it is a static class and its usage is as simple as:

    var list = new List<int>();
    AutoInvoke.Invoke(list, "add", 10);

or for resolving overloaded methods

public class PayloadHandler
{
    public int AHandledCount { get; set; } = 0;
    public int BHandledCount { get; set; } = 0;
    public void Handle(APayload payload) { AHandledCount++; }
    public void Handle(BPayload payload) { BHandledCount++; }
}

public void Invoke_WithSpecificType()
{
    var _handler = new PayloadHandler();

    AutoInvoke.Invoke(_handler, "Handle", new APayload());
    Assert.Equal(1, _handler.AHandledCount);

    AutoInvoke.Invoke(_handler, "Handle", new BPayload());
    AutoInvoke.Invoke(_handler, "Handle", new BPayload());
    Assert.Equal(1, _handler.AHandledCount);
    Assert.Equal(2, _handler.BHandledCount);
}

It is in alpha stage but the basic functionality is there.

The main open issues are

  • Cannot handle extension methods
  • Cannot await async methods (will return Task)

nuget
repository

Top comments (0)