依赖注入以解决与运行时数据的依赖关系
Dependency Injection to resolve dependency with runtime data
我正在为我的网络 api 项目使用简单的注入器。我有一项服务需要会话令牌才能实例化。
public class CustomerService
{
public CustomerService(Auth auth, IRepositoryFactory repositoryFactory)
{
// make post call to another web api for validation
SomeWebApiCallToValidateAuth.vaildate(auth);
}
}
因此对于此服务,它需要一个身份验证令牌和一个 repositoryFactory。我希望它能够注入 auth 参数(来自 http web 请求),同时使用注册到容器的指定实现解析存储库工厂。
但我不确定如何使用简单的注入器注册它,或者是否有解决方法。任何帮助都会很棒。谢谢
您当前的方法有几个缺点:
- 您将运行时数据注入组件的构造函数,can lead to complications。
- 您使用了抽象工厂,is often not the best abstraction。
- 您的构造函数调用验证,而它 should do nothing other than storing its incoming dependencies. This way you can compose your object graphs with confidence.
关于工厂:注入 IRepository
而不是 IRepositoryFactory
。这可能需要您将真实存储库隐藏在代理后面,如 .
所述
关于Auth
值,看需要,但是如果Auth
值是CustomerService
的API
的重要组成部分,那么就可以加上Auth
作为 CustomerService
方法的参数。如果它是一个实现细节,则注入某种 IAuthProvider
抽象,允许您在运行时(在构建对象图之后)检索值。同样,这一切都在 this article.
中进行了描述
我正在为我的网络 api 项目使用简单的注入器。我有一项服务需要会话令牌才能实例化。
public class CustomerService
{
public CustomerService(Auth auth, IRepositoryFactory repositoryFactory)
{
// make post call to another web api for validation
SomeWebApiCallToValidateAuth.vaildate(auth);
}
}
因此对于此服务,它需要一个身份验证令牌和一个 repositoryFactory。我希望它能够注入 auth 参数(来自 http web 请求),同时使用注册到容器的指定实现解析存储库工厂。
但我不确定如何使用简单的注入器注册它,或者是否有解决方法。任何帮助都会很棒。谢谢
您当前的方法有几个缺点:
- 您将运行时数据注入组件的构造函数,can lead to complications。
- 您使用了抽象工厂,is often not the best abstraction。
- 您的构造函数调用验证,而它 should do nothing other than storing its incoming dependencies. This way you can compose your object graphs with confidence.
关于工厂:注入 IRepository
而不是 IRepositoryFactory
。这可能需要您将真实存储库隐藏在代理后面,如
关于Auth
值,看需要,但是如果Auth
值是CustomerService
的API
的重要组成部分,那么就可以加上Auth
作为 CustomerService
方法的参数。如果它是一个实现细节,则注入某种 IAuthProvider
抽象,允许您在运行时(在构建对象图之后)检索值。同样,这一切都在 this article.