0

I have following issue: I'm working on a system which processes various Types of "Events" which all trigger a different business logic (called EventProcessor in this example). The code is now refactored to a point where I now want one generic "Eventprocessor" which is able to, dependent on the ingested event type, returns the correct Businesslogic to process this event.

    public class GenericEventProcessor
    {
        private IServiceProvider _serviceProvider { get; }

        public GenericEventProcessor(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
        }

        public Task RunAsync(string eventCarrierString, ILogger log, string functionName)
        {
            var eventCarrier = JsonConvert.DeserializeObject<EventCarrier>(eventCarrierString);

            Type eventType= typeof(eventCarrier.EventType);

            var eventProcessor =_serviceProvider.GetService(IEventProcessor<eventType>)

            eventProcessor.RunAsync(eventCarrier.eventString, log, functionName)
        }
    }

The event is passed in as a "EventCarrier" Object which has two properties, -A Enum telling which type of Event this is, -And another string which contains the actual event.

The actual business logic is implemented in various EventProcessors which implement a IEventProcessor Interface, where T is some Event.

This apparently does not work (because i can't pass the eventType into the Generic Interface) and i have the feeling that i'm doing this completly wrong.

What would you suggest to implement something like this? (Or get this to run!)

Thanks in advance, Matthias

HMattes
  • 1
  • 1
  • 1
    Possible duplicate of [Calling a generic function with a type parameter determined at runtime](https://stackoverflow.com/questions/1455977/calling-a-generic-function-with-a-type-parameter-determined-at-runtime) – madreflection Apr 29 '19 at 20:39
  • are you trying to invoke `GetService()` or `GetService(Type)` ? – Xiaoy312 Apr 29 '19 at 20:44
  • Rephrased the title a bit. @Xiaoy312 I try to invoke GetService(). – HMattes Apr 29 '19 at 20:54

1 Answers1

2

Try to use MakeGenericType to build required type at runtime

Type eventType= typeof(eventCarrier.EventType);
            Type processor  = typeof(IEventProcessor<>);
             Type generic = processor.MakeGenericType(eventType);
        var eventProcessor =_serviceProvider.GetService(generic);
Sergey K
  • 4,071
  • 2
  • 23
  • 34