[英]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'错误消息:System.ArgumentException:'<>f__AnonymousType2`1[System.String]' 类型的对象无法转换为'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我正在尝试调用 GetResponse 但使用反射
var client = mediator.CreateRequestClient<IRequestSimple>();
var response = client.GetResponse<IResponseSimple>(new { });
There is my issue, I need to specify type to calling GetResponse有我的问题,我需要指定类型来调用 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.