samedi 5 mai 2018

C# unable to delegate event handler with Task return type method

I'm working to have a custom asynchronous event domain handling, when I tried to create a delegate for Task HandleEvent(TEvent @event) method -that is responsible for async execution of events, once the return type is Task then I have a exception of

System.ArgumentException: 'Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.'

public IDisposable RegisterHandler(object handler)
        {
            Contract.Requires(handler != null);

            var interfaceType = handler.GetType().GetTypeInfo().GetInterfaces()
                .SingleOrDefault(t => t.GetGenericTypeDefinition() == typeof(IEventHandler<>));

            if (interfaceType == null)
            {
                throw new ArgumentException(string.Format("Supplied parameter does not implement {0} interface.", nameof(IEventHandler<object>)));
            }

            var eventType = interfaceType.GenericTypeArguments[0];

            var stream = this.eventStreams[eventType];
            var streamType = stream.GetType();

            if (this.eventStreams == null)
            {
                throw new KeyNotFoundException(string.Format("Event stream for '{0}' was not found.", eventType.Name));
            }

            var handleEvent = handler.GetType().GetTypeInfo().GetMethod(nameof(IEventHandler<object>.HandleEvent));
            var actionType = typeof(Action<>).MakeGenericType(eventType);

            var del = handleEvent.CreateDelegate(actionType, handler);

            var method = streamType.GetTypeInfo().GetMethods().First(
                t =>
                    t.Name == nameof(IEventStream<object>.Subscribe) &&
                    t.GetParameters().FirstOrDefault()?.ParameterType.GetGenericTypeDefinition() == typeof(Action<>));

            return (IDisposable)method.Invoke(stream, new object[] { del });
        }

How can I create a delegate for the concerned method?





Aucun commentaire:

Enregistrer un commentaire