DEV Community

Thomas Sarmis
Thomas Sarmis

Posted on • Edited on

2 1

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay