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.7 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 a @Microsoft.Extensions.DependencyInjection.ServiceCollection.
  11. 2. Add the dependencies to the service collection that you wish
  12. to use in the modules.
  13. 3. Build the service collection into a service provider.
  14. 4. Pass the service collection into @Discord.Commands.CommandService.AddModulesAsync* / @Discord.Commands.CommandService.AddModuleAsync* , @Discord.Commands.CommandService.ExecuteAsync* .
  15. ### Example - Setting up Injection
  16. [!code-csharp[IServiceProvider Setup](samples/dependency-injection/dependency_map_setup.cs)]
  17. ## Usage in Modules
  18. In the constructor of your module, any parameters will be filled in by
  19. the @System.IServiceProvider that you've passed.
  20. Any publicly settable properties will also be filled in the same
  21. manner.
  22. > [!NOTE]
  23. > Annotating a property with a [DontInjectAttribute] attribute will
  24. > prevent the property from being injected.
  25. > [!NOTE]
  26. > If you accept `CommandService` or `IServiceProvider` as a parameter
  27. > in your constructor or as an injectable property, these entries will
  28. > be filled by the `CommandService` that the module is loaded from and
  29. > the `IServiceProvider` that is passed into it respectively.
  30. ### Example - Injection in Modules
  31. [!code-csharp[Injection Modules](samples/dependency-injection/dependency_module.cs)]
  32. [!code-csharp[Disallow Dependency Injection](samples/dependency-injection/dependency_module_noinject.cs)]
  33. [DontInjectAttribute]: xref:Discord.Commands.DontInjectAttribute