dimanche 24 janvier 2021

Cast object to Task

It's a little bit difficult to explain, I apologies for that. But I need help. I'm working on generic approach for events. All my code base on eShopOnContainers example but my handlers should return a value.

In eShopOnContainers there is just Task as a return type, so they can easy

var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });

Let's say I have

public interface IRequestMessageHandler<in TRequest, TReply>
    {
        Task<TReply> Handle(TRequest request);
    }

In my case, I need to cast to Task<T>. Type for T store in variable

Type concreteHandlerType = typeof(IRequestMessageHandler<,>).MakeGenericType(subscription.RequestType, subscription.ReplyType);
Type concreteReplyType = typeof(Task<>).MakeGenericType(subscription.ReplyType);

Then I need cast result to concreteReplyType

var reply = await (concreteReplyType)concreteType.GetMethod("Handle")?.Invoke(handler, new[] { integrationEvent });

Please help me because I don't understand how it is possible. Thank you in advance. Please let me know what information should I add to help you more understand.

Fiddle with code to reproduce https://dotnetfiddle.net/X3m4A1





Aucun commentaire:

Enregistrer un commentaire