Home >Backend Development >C++ >Should I Inject Dependencies into Attributes?

Should I Inject Dependencies into Attributes?

DDD
DDDOriginal
2025-01-15 08:24:44569browse

Should I Inject Dependencies into Attributes?

Property Dependency Injection: Not Recommended

Property injection should generally be avoided due to limitations of CLR and frameworks such as MVC and Web API.

Question

In your code, injecting IPermissionService into AuthorizeAttribute via property injection will be problematic because at runtime permissionService will be null.

Solution

Please consider the following:

Option 1: Separate data and behavior

  • Extract logic from attributes into a service
  • Register the service in the container
  • Use attributes to parse and call the service's method

Option 2: Use Humble Objects

  • Move all logic in properties into custom services
  • Register the service in the container
  • Let the property's AuthorizeCore method resolve the service and call its method

Which option to choose?

  • Option 1: For design simplicity, multiple properties, or defining properties in an assembly independent of MVC.
  • Option 2: In other cases, a more pragmatic approach.

The above is the detailed content of Should I Inject Dependencies into Attributes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn