依赖注入可解决运行时数据的依赖 [英] Dependency Injection to resolve dependency with runtime data

查看:54
本文介绍了依赖注入可解决运行时数据的依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的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:

  • 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.

这篇关于依赖注入可解决运行时数据的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆