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!)
}
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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With