Aspects, like other components, may have dependencies on other application services. Aspects may be bound to the abstract interface of a service, and may need to resolve the dependency at run time.
However, two characteristics of aspects prevent the use of the approaches that are usual with dependency injection containers:
Aspects are instantiated at build time, and dependency injection containers exist only at run time.
Aspects typically have a static scope. Unless they implement IInstanceScopedAspect, aspect instances are stored in static fields, even when applied to instance members.
These characteristics are not an obstacle to using service containers, but you must follow different patterns.
This section presents several ways to consume dependencies from an aspect:
- Receiving Dependencies from the Constructors of the Target Class: the aspect requests a service, which the target class receives from its constructors, for instance from Microsoft.Extensions.DependencyInjection. This is the approach to prefer when the objects are created by a container.
- Using a Global Composition Container
- Using a Global Service Locator
- Using Dynamic Dependency Resolution
- Using Contextual Dependency Resolution
- Importing Dependencies from the Target Object