Skip to content

Add Commands Explicitly to ServiceCollection #391

@Kahbazi

Description

@Kahbazi

Hello @csharpfritz .
Right now all IBasicCommand and IExtendedCommand are got via scanning Assembly and added to IServiceCollection with singleton lifetime.

public static void RegisterCommands(IServiceCollection services)
{
// Register basic commands
foreach (var type in typeof(FritzBot).Assembly.GetTypes()
.Where(t => typeof(IBasicCommand)
.IsAssignableFrom(t) && !t.IsAbstract && t.IsClass))
{
services.AddSingleton(typeof(IBasicCommand), type);
}
// Register extended commands
foreach (var type in typeof(FritzBot).Assembly.GetTypes()
.Where(t => typeof(IExtendedCommand)
.IsAssignableFrom(t) && !t.IsAbstract && t.IsClass))
{
services.AddSingleton(typeof(IExtendedCommand), type);
}
}

I'm suggesting changing this behavior to adding commands explicitly in startup for two reasons :

  1. In order to inject a scoped service like DbContext, the command needs to be scoped or transient.
  2. We could prevent adding some command in startup based on configuration and prevent running a command (even CanExecute).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions