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.

injection.md 1.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. ---
  2. uid: Guides.DI.Injection
  3. title: Injection
  4. ---
  5. # Injecting instances within the provider
  6. You can inject registered services into any class that is registered to the `IServiceProvider`.
  7. This can be done through property or constructor.
  8. > [!NOTE]
  9. > As mentioned above, the dependency *and* the target class have to be registered in order for the serviceprovider to resolve it.
  10. ## Injecting through a constructor
  11. Services can be injected from the constructor of the class.
  12. This is the preferred approach, because it automatically locks the readonly field in place with the provided service and isn't accessible outside of the class.
  13. [!code-csharp[Constructor Injection](samples/ctor-injecting.cs)]
  14. ## Injecting through properties
  15. Injecting through properties is also allowed as follows.
  16. [!code-csharp[Property Injection](samples/property-injecting.cs)]
  17. > [!WARNING]
  18. > Dependency Injection will not resolve missing services in property injection, and it will not pick a constructor instead.
  19. > If a publically accessible property is attempted to be injected and its service is missing, the application will throw an error.
  20. ## Using the provider itself
  21. You can also access the provider reference itself from injecting it into a class. There are multiple use cases for this:
  22. - Allowing libraries (Like Discord.Net) to access your provider internally.
  23. - Injecting optional dependencies.
  24. - Calling methods on the provider itself if necessary, this is often done for creating scopes.
  25. [!code-csharp[Provider Injection](samples/provider.cs)]
  26. > [!NOTE]
  27. > It is important to keep in mind that the provider will pick the 'biggest' available constructor.
  28. > If you choose to introduce multiple constructors,
  29. > keep in mind that services missing from one constructor may have the provider pick another one that *is* available instead of throwing an exception.