DSharpPlus / DSharpPlus

A .NET library for making bots using the Discord API.
https://discord.gg/dsharpplus
MIT License
1.25k stars 306 forks source link

Add `AddEventHandlers(Type t, ...)` as alternative to `AddEventHandlers<T>(...)` #2116

Closed ikegami closed 1 week ago

ikegami commented 3 weeks ago

Description

In EventHandlingBuilder, we have

public EventHandlingBuilder AddEventHandlers<T>(ServiceLifetime lifetime = ServiceLifetime.Transient) where T : IEventHandler

I request the addition of an alternative interface:

public EventHandlingBuilder AddEventHandlers(Type t, ServiceLifetime lifetime = ServiceLifetime.Transient)

This would allow the following:

IEnumerable<Type> event_handler_module =
[
    typeof(Module.A),
    typeof(Module.B),
    typeof(Module.C),
];

var intents =
    ( SlashCommandProcessor.RequiredIntents
    | TextCommandProcessor.RequiredIntents
    );

foreach (var event_handler_module in event_handler_modules)
    intents |= GetModuleIntents(event_handler_module);

...

builder.ConfigureEventHandlers(
    ehb =>
    {
        foreach (var event_handler_module in event_handler_modules)
            ehb.AddEventHandlers(event_handler_module, ServiceLifetime.Singleton);
    }
);

It's a almost trivial addition.

Specify the libraries you want this feature request to affect

DSharpPlus, the core library

Other considerations

No response

ikegami commented 2 weeks ago

Without the change to the library, this can be achieved using this word salad:

builder.ConfigureEventHandlers(
    ehb =>
    {
        // The loop below performs the following for each module without hardcoding the type:
        // ehb.AddEventHandlers<...>(ServiceLifetime.Singleton);
        var method = ehb.GetType().GetMethod(nameof(EventHandlingBuilder.AddEventHandlers));
        foreach (var event_handler_module in event_handler_modules)
            method.MakeGenericMethod(event_handler_module).Invoke(ehb, [ServiceLifetime.Singleton]);
    }
);
ikegami commented 1 week ago

Thanks :)