I'm attempting to automatically register request handling classes with reflection.
This is an example of manually adding a handler for execution of a certain request.
// generic manual method of registration
server.RegisterHandler<GetData>(base.ExecuteMessage);
Here is the attempt to register with reflection. The invoke method will not accept the 'ExecuteMessage' method getting the error "Error CS0428 Cannot convert method group 'ExecuteMessage' to non-delegate type 'object'. Did you intend to invoke the method?".
// registration with reflection
foreach (var type in serviceTypes)
{
// registerHandlerMethod definition: RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn)
// ExecuteMessage definition: object ExecuteMessage(IMessage message)
registerHandlerMethod.MakeGenericMethod(type).Invoke(server, new object[] { base.ExecuteMessage });
}
Is it possible to cast the ExecuteMessage method in any way to get this to work?
Edit: Added example with problem below
class Program
{
static void Main(string[] args)
{
var server = new Server();
// generic manual method of registration
server.RegisterHandler<GetData>(ExecuteMessage);
// registration with reflection
var serviceTypes = new List<Type> { typeof(GetData) };
var registerHandlerMethod = typeof(Server).GetMethod(nameof(Server.RegisterHandler));
foreach (var type in serviceTypes)
{
registerHandlerMethod.MakeGenericMethod(type).Invoke(server, new object[] { ExecuteMessage });
}
}
static object ExecuteMessage(IMessage message)
{
return null;
}
internal class GetData
{
}
internal interface IMessage<T> : IMessage
{
}
internal interface IMessage
{
}
internal class Server
{
internal void RegisterHandler<T>(Func<IMessage<T>, object> processMessageFn)
{
}
}
}
Aucun commentaire:
Enregistrer un commentaire