You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dependency-injection.md 1.3 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. ---
  2. uid: Guides.Commands.DI
  3. title: Dependency Injection
  4. ---
  5. # Dependency Injection
  6. The Command Service is bundled with a very barebone Dependency
  7. Injection service for your convenience. It is recommended that you use
  8. DI when writing your modules.
  9. ## Setup
  10. 1. Create an @System.IServiceProvider.
  11. 2. Add the dependencies to the service collection that you wish
  12. to use in the modules.
  13. 3. Pass the service collection into `AddModulesAsync`.
  14. ### Example - Setting up Injection
  15. [!code-csharp[IServiceProvider Setup](samples/dependency_map_setup.cs)]
  16. ## Usage in Modules
  17. In the constructor of your module, any parameters will be filled in by
  18. the @System.IServiceProvider that you've passed.
  19. Any publicly settable properties will also be filled in the same
  20. manner.
  21. > [!NOTE]
  22. > Annotating a property with a [DontInjectAttribute] attribute will
  23. > prevent the property from being injected.
  24. > [!NOTE]
  25. > If you accept `CommandService` or `IServiceProvider` as a parameter
  26. > in your constructor or as an injectable property, these entries will
  27. > be filled by the `CommandService` that the module is loaded from and
  28. > the `IServiceProvider` that is passed into it respectively.
  29. ### Example - Injection in Modules
  30. [!code-csharp[IServiceProvider in Modules](samples/dependency_module.cs)]
  31. [DontInjectAttribute]: xref:Discord.Commands.DontInjectAttribute