Dependency Injection
The Text Command Service is bundled with a very barebone Dependency
Injection service for your convenience. It is recommended that you use
DI when writing your modules.
[!WARNING]
If you were brought here from the Interaction Service guides,
make sure to replace all namespaces that imply Discord.Commands
with Discord.Interactions
Setup
- Create a @Microsoft.Extensions.DependencyInjection.ServiceCollection.
- Add the dependencies to the service collection that you wish
to use in the modules.
- Build the service collection into a service provider.
- Pass the service collection into @Discord.Commands.CommandService.AddModulesAsync* / @Discord.Commands.CommandService.AddModuleAsync* , @Discord.Commands.CommandService.ExecuteAsync* .
Example - Setting up Injection
[!code-csharpIServiceProvider Setup]
Usage in Modules
In the constructor of your module, any parameters will be filled in by
the @System.IServiceProvider that you've passed.
Any publicly settable properties will also be filled in the same
manner.
[!NOTE]
Annotating a property with a DontInjectAttribute attribute will
prevent the property from being injected.
[!NOTE]
If you accept CommandService
or IServiceProvider
as a parameter
in your constructor or as an injectable property, these entries will
be filled by the CommandService
that the module is loaded from and
the IServiceProvider
that is passed into it respectively.
Example - Injection in Modules
[!code-csharpInjection Modules]
[!code-csharpDisallow Dependency Injection]