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.2 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. [!code-csharp[IServiceProvider Setup](samples/dependency_map_setup.cs)]
  15. ## Usage in Modules
  16. In the constructor of your module, any parameters will be filled in by
  17. the @System.IServiceProvider that you've passed.
  18. Any publicly settable properties will also be filled in the same
  19. manner.
  20. > [!NOTE]
  21. > Annotating a property with a [DontInjectAttribute] attribute will
  22. > prevent the property from being injected.
  23. > [!NOTE]
  24. > If you accept `CommandService` or `IServiceProvider` as a parameter
  25. > in your constructor or as an injectable property, these entries will
  26. > be filled by the `CommandService` that the module is loaded from and
  27. > the `ServiceProvider` that is passed into it respectively.
  28. [!code-csharp[ServiceProvider in Modules](samples/dependency_module.cs)]
  29. [DontInjectAttribute]: xref:Discord.Commands.DontInjectAttribute