简体   繁体   中英

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);

I just create method and invoke that

public static async Task<Tout> GetResponse<Tin, Tout>(object request) where Tin : class where Tout : class
{
  var requestClient = Program.mediator.CreateRequestClient<Tin>();
  var response = await requestClient.GetResponse<Tout>(request);
  return response.Message;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM