samedi 29 janvier 2022

How to call generic Method from generic Interface c#?

Error Message:System.ArgumentException: 'Object of type '<>f__AnonymousType2`1[System.String]' cannot be converted to type 'ConsoleApp2.IRequestSimple'

There are my types Request/Response

    public interface IRequestSimple
    {
        public string Field { get; set; }
    }

    public interface IResponseSimple
    {
        public string Answer { get; set; }
    }

    public class MyConsumer : IConsumer<IRequestSimple>
    {
        public async Task Consume(ConsumeContext<IRequestSimple> context)
        {
            Console.WriteLine(context.Message.Field);
            await context.RespondAsync<IResponseSimple>(new { Answer = "Good job" });
        }
    }

I'm trying to call GetResponse but using reflection

var client = mediator.CreateRequestClient<IRequestSimple>();
var response = client.GetResponse<IResponseSimple>(new { });

There is my issue, I need to specify type to calling GetResponse

var requestType = typeof(IRequestSimple);
var responseType = typeof(IResponseSimple);
            
Type type = mediator.GetType();
var methodInfo = typeof(IClientFactory).GetMethods().Where(s => s.Name == "CreateRequestClient" && s.IsGenericMethod).First();
var genericMethod = methodInfo.MakeGenericMethod(requestType);
dynamic requestClient = genericMethod.Invoke(mediator, new object[] { Missing.Value });

Type type1 = requestClient.GetType();
var methodInfo1 = type1 .GetMethods().Where(s => s.Name == "GetResponse").First();
var genericMethod1 = methodInfo1.MakeGenericMethod(responseType);
//Here is my requestClient should be with specified type
var task = (Task)genericMethod1.Invoke(requestClient, new object[] { new { Field = "1" }, Missing.Value, Missing.Value });
await task.ConfigureAwait(false);





Aucun commentaire:

Enregistrer un commentaire