I need to do a specific thing depending on Type, not sure how to implement it

53 views Asked by At

I have been building a consumer where each message comes with a SchemaType which is a AssemblyQualifiedName and also a Payload which is the object of this type.

In order to cast it I have come up with this:

Type innerType = Type.GetType(values["SchemaType"]);
Type eventWithInnerType = typeof(Event<>).MakeGenericType(new[] { innerType });
var @event = JsonConvert.DeserializeObject(messageBody, eventWithInnerType);

Now I should take a different action depending on innerType. But I am quite stuck, not sure what would be the best approach to do so.

For example: innerType could be to call a service that sends an email, next message could be to call a service to persist something into the database.

1

There are 1 answers

1
Tanveer Badar On BEST ANSWER

Version 1:

Defining a set of overload ProcessEvent() which take various Event<T>, varying the T, sounds like a good idea to me.

ProcessEvent(Event<DbQuery> evt);
ProcessEvent(Event<ServiceCall> evt);

Version 2:

Short of that, if your T contains an EventType which you can surface through Event<T>.EventType, a switch expression may be the next best thing.

var outcome = evt.EventType switch
{
    EventType.DbCall => CallDatabase(evt),
    EventType.CallService => CallService(evt),
    // so forth
};