Dependency Injection to resolve dependency with runtime data

坚强是说给别人听的谎言 提交于 2019-12-14 03:58:34

问题


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);
   }
}

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.


回答1:


Your current approach has several downsides:

  • You inject runtime data into the constructor of your component, which is an code smell.
  • You make use of an Abstract Factory, which is a code smell as well.
  • 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.

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.

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.



来源:https://stackoverflow.com/questions/45850250/dependency-injection-to-resolve-dependency-with-runtime-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!