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.

scaling.md 1.6 kB

123456789101112131415161718192021222324252627282930313233343536373839
  1. ---
  2. uid: Guides.DI.Scaling
  3. title: Scaling your DI
  4. ---
  5. # Scaling your DI
  6. Dependency injection has a lot of use cases, and is very suitable for scaled applications.
  7. There are a few ways to make registering & using services easier in large amounts.
  8. ## Using a range of services.
  9. If you have a lot of services that all have the same use such as handling an event or serving a module,
  10. you can register and inject them all at once by some requirements:
  11. - All classes need to inherit a single interface or abstract type.
  12. - While not required, it is preferred if the interface and types share a method to call on request.
  13. - You need to register a class that all the types can be injected into.
  14. ### Registering implicitly
  15. Registering all the types is done through getting all types in the assembly and checking if they inherit the target interface.
  16. [!code-csharp[Registering](samples/implicit-registration.cs)]
  17. > [!NOTE]
  18. > As seen above, the interfaceType and activatorType are undefined. For our usecase below, these are `IService` and `ServiceActivator` in order.
  19. ### Using implicit dependencies
  20. In order to use the implicit dependencies, you have to get access to the activator you registered earlier.
  21. [!code-csharp[Accessing the activator](samples/access-activator.cs)]
  22. When the activator is accessed and the `ActivateAsync()` method is called, the following code will be executed:
  23. [!code-csharp[Executing the activator](samples/enumeration.cs)]
  24. As a result of this, all the services that were registered with `IService` as its implementation type will execute their starting code, and start up.