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.

services.md 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. ---
  2. uid: Guides.DI.Services
  3. title: Using DI in Interaction & Command Frameworks
  4. ---
  5. # DI in the Interaction- & Command Service
  6. For both the Interaction- and Command Service modules, DI is quite straight-forward to use.
  7. You can inject any service into modules without the modules having to be registered to the provider.
  8. Discord.Net resolves your dependencies internally.
  9. > [!WARNING]
  10. > The way DI is used in the Interaction- & Command Service are nearly identical, except for one detail:
  11. > [Resolving Module Dependencies](xref:Guides.IntFw.Intro#resolving-module-dependencies)
  12. ## Registering the Service
  13. Thanks to earlier described behavior of allowing already registered members as parameters of the available ctors,
  14. The socket client & configuration will automatically be acknowledged and the XService(client, config) overload will be used.
  15. [!code-csharp[Service Registration](samples/service-registration.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. [!code-csharp[Module Injection](samples/modules.cs)]
  22. If you accept `Command/InteractionService` or `IServiceProvider` as a parameter in your constructor or as an injectable property,
  23. these entries will be filled by the `Command/InteractionService` that the module is loaded from and the `IServiceProvider` that is passed into it respectively.
  24. > [!NOTE]
  25. > Annotating a property with a [DontInjectAttribute] attribute will
  26. > prevent the property from being injected.
  27. ## Services
  28. Because modules are transient of nature and will reinstantiate on every request,
  29. it is suggested to create a singleton service behind it to hold values across multiple command executions.
  30. [!code-csharp[Services](samples/services.cs)]