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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. ---
  2. uid: FAQ.Commands.DI
  3. title: Questions about Dependency Injection with Commands
  4. ---
  5. # Dependency-injection-related Questions
  6. In the following section, you will find common questions and answers
  7. to utilizing dependency injection with @Discord.Commands, as well as
  8. common troubleshooting steps regarding DI.
  9. ## What is a service? Why does my module not hold any data after execution?
  10. In Discord.Net, modules are created similarly to ASP.NET, meaning
  11. that they have a transient nature; modules are spawned whenever a
  12. request is received, and are killed from memory when the execution
  13. finishes. In other words, you cannot store persistent
  14. data inside a module. Consider using a service if you wish to
  15. workaround this.
  16. Service is often used to hold data externally so that they persist
  17. throughout execution. Think of it like a chest that holds
  18. whatever you throw at it that won't be affected by anything unless
  19. you want it to. Note that you should also learn Microsoft's
  20. implementation of [Dependency Injection] \([video]) before proceeding,
  21. as well as how it works in [Discord.Net](xref:Guides.TextCommands.DI#usage-in-modules).
  22. A brief example of service and dependency injection can be seen below.
  23. [!code-csharp[DI](samples/DI.cs)]
  24. [Dependency Injection]: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
  25. [video]: https://www.youtube.com/watch?v=QtDTfn8YxXg
  26. ## Why is my `CommandService` complaining about a missing dependency?
  27. If you encounter an error similar to `Failed to create MyModule,
  28. dependency MyExternalDependency was not found.`, you may have
  29. forgotten to add the external dependency to the dependency container.
  30. Starting from Discord.Net 2.0, all dependencies required by each
  31. module must be present when the module is loaded into the
  32. [CommandService]. This means when loading the module, you must pass a
  33. valid [IServiceProvider] with the dependency loaded before the module
  34. can be successfully registered.
  35. For example, if your module, `MyModule`, requests a `DatabaseService`
  36. in its constructor, the `DatabaseService` must be present in the
  37. [IServiceProvider] when registering `MyModule`.
  38. [!code-csharp[Missing Dependencies](samples/missing-dep.cs)]
  39. [IServiceProvider]: xref:System.IServiceProvider
  40. [CommandService]: xref:Discord.Commands.CommandService