依赖注入可解决运行时数据的依赖

编程入门 行业动态 更新时间:2024-10-24 22:30:19
本文介绍了依赖注入可解决运行时数据的依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为我的Web api项目使用简单的注入器。我有一项需要会话令牌才能实例化的服务。

I am using simple injector for my web api project. I have a service which requires a session token in order for it to instantiate.

public class CustomerService { public CustomerService(Auth auth, IRepositoryFactory repositoryFactory) { // make post call to another web api for validation SomeWebApiCallToValidateAuth.vaildate(auth); } }

因此,对于此服务,它需要一个auth令牌和一个repositoryFactory。我希望它能够注入auth参数(来自http Web请求),并同时使用注册到容器中的指定已实现多数票来解析存储库工厂。

So for this service, it requires an auth token and a repositoryFactory. I want it to be able to inject the auth parameter (which comes from the http web request) and at the same time to resolve the repository factory with the specified implemented thats registered to the container.

但是我不确定如何使用简单的注入器注册它,或者是否有解决方法。任何帮助都会很棒。谢谢。

But I am not sure how to register this with simple injector or if there is a way around it. Any help would be great. Thanks.

推荐答案

您当前的方法有几个缺点:

Your current approach has several downsides:

  • 您将运行时数据注入到组件的构造函数中,该构造函数会导致并发症。
  • 您使用了 Abstract Factory ,其中通常不是最好的抽象。
  • b $ b
  • 您的构造函数会调用验证,而它的除了存储外,应该什么也不做它的传入依赖项。这样,您可以自信地组成对象图。
  • You inject runtime data into the constructor of your component, which can lead to complications.
  • You make use of an Abstract Factory, which is often not the best abstraction.
  • Your constructor invokes validation, while it should do nothing other than storing its incoming dependencies. This way you can compose your object graphs with confidence.

关于工厂:注入 IRepository 而不是 IRepositoryFactory 。如此处所述。

Concerning the factory: Inject an IRepository rather than an IRepositoryFactory. This might require you to hide the real repository behind a proxy, as explained here.

关于 Auth 值,这取决于需要,但是 Auth 值是否是 CustomerService 的 API ,这证明添加 Auth 作为参数 CustomerService 的方法。如果它是实现的详细信息,请注入某种 IAuthProvider 抽象,该抽象允许您在运行时(构建对象图之后)检索值。同样,这一切都在 。

Concerning the Auth value, it depends on the need, but if the Auth value is an important part of the API of CustomerService, this justifies adding Auth as argument on the methods of CustomerService. If it is an implementation detail, inject an IAuthProvider abstraction of some sort that allows you to retrieve the value at runtime (after the object graph is built). Again, this all is described in this article.

更多推荐

依赖注入可解决运行时数据的依赖

本文发布于:2023-11-15 05:26:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!