Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as a method name using dynamic objects

Tags:

c#

signalr

In SignalR there is public property defined in the HubConnectionContext as such:

public dynamic All { get; set; }

This enables users to call it like: All.someMethodName(); which is brilliant.

I now would like to call this using an incoming parameter in my function. How can I do this?

As in: All.<my variable as method name>();

Is there any way of doing this?

Thanks

EDIT example:

    public void AcceptSignal(string methodToCall, string msg)
    {
        Clients.All.someMethod(msg);       // THIS WORKS
        Clients.All.<methodToCall>(msg);   // THIS DOES NOT WORK (But I would like it to!)
    }
like image 516
Marcel Avatar asked Apr 18 '13 09:04

Marcel


2 Answers

While I love all the fun reflection answers, there's a much simpler and faster way to invoke client hub methods using a string as the method Name.

Clients.All, Clients.Others, Clients.Caller, Clients.AllExcept(connectionIds), Clients.Group(groupName), Clients.OthersInGrouop(groupName), and Clients.Client(connectionId) are all dynamic objects, but they also all implement the IClientProxy interface.

You can cast any of these dynamic objects to an IClientProxy, and then call Invoke(methodName, args...):

public void AcceptSignal(string methodToCall, string msg)
{

    IClientProxy proxy = Clients.All;
    proxy.Invoke(methodToCall, msg);
}
like image 191
halter73 Avatar answered Oct 30 '22 05:10

halter73


You can use reflection to achieve this:

Type allType = All.GetType();
// GetType() may return null in relation to dynamics objects
if (allType != null)
{
    MethodInfo methodInfo = allType.GetMethod(methodToCall);
    methodInfo.Invoke(All, null);
}
like image 26
John Willemse Avatar answered Oct 30 '22 04:10

John Willemse