❔ OOP Event Handler implementation

Hi, I am using D#+ (DiscordSharpPlus) and I am trying to figure out a class based implementation for handling events, instead of doing something like client.Ready += OnReady where I subscribe to the event in a functional programming way, I would like to have a class like this
public class BaseEventHandler {
public EventType EventType; // EventType is an enum
// See https://github.com/Naamloos/ModCore/blob/5d9a993619bce03b84ce922dd80ff7cd7c966691/ModCore/Extensions/Enums/EventType.cs

public BaseEventHandler(EventType eventType) => EventType = eventType;
}
public class BaseEventHandler {
public EventType EventType; // EventType is an enum
// See https://github.com/Naamloos/ModCore/blob/5d9a993619bce03b84ce922dd80ff7cd7c966691/ModCore/Extensions/Enums/EventType.cs

public BaseEventHandler(EventType eventType) => EventType = eventType;
}
public class OnReadyEventHandler : BaseEventHandler {
private readonly DataContext _dataContext;

public OnReadyEventListener(DataContext dataContext): base(EventType.Ready) {
_dataContext = dataContext;
}

public Task Handler(DiscordClient client) {
// Handle event in here
}
}
public class OnReadyEventHandler : BaseEventHandler {
private readonly DataContext _dataContext;

public OnReadyEventListener(DataContext dataContext): base(EventType.Ready) {
_dataContext = dataContext;
}

public Task Handler(DiscordClient client) {
// Handle event in here
}
}
I preferably want to use something like assembly scanning to automatically get these Handlers but I am not familiar enough wit Reflection to get the parameter passed to base and then also somehow connecting this to the event (I guess I need to use addEventListener())
public void Register(Assembly assembly) {
var handlers = assembly.GetTypes().Where(x =>
x.IsSubclassOf(typeof(BaseEventHandler)) &&
!x.IsInterface &&
!x.IsAbstract
)

for (Type handler in handlers) {
var _event = client.GetType().GetEvents().First(ev => ev.Name == handler.EventType.ToString());
// How do I subscribe now?
}


}
public void Register(Assembly assembly) {
var handlers = assembly.GetTypes().Where(x =>
x.IsSubclassOf(typeof(BaseEventHandler)) &&
!x.IsInterface &&
!x.IsAbstract
)

for (Type handler in handlers) {
var _event = client.GetType().GetEvents().First(ev => ev.Name == handler.EventType.ToString());
// How do I subscribe now?
}


}
2 Replies
BlackBearFTW
BlackBearFTW2y ago
I'm using the EventType enum because I would like to avoid typos
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.